Solution in JAVA by 5 lines

  • 0

    Given a sorted array and a target value,we should find the position of array [i] >= target.
    When nums[i] equals to the given value, we get the right position of searching.When nums[i] beyond the given value,we have found the right position of inserting.

    class Solution {
        public int searchInsert(int[] nums, int target) {
            if(nums[nums.length-1]<target)return nums.length;
            int index = 0;
            for (int i = 0; i < nums.length; i++) {
    	    if(nums[i]>=target) { index = i;break;}
        	return index;

    Complexity analysis

    • Time complexity : O(n). Assume the array has a total of n elements, i traverse at most n steps,and at least 1 step.
    • Space complexity : O(1).

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.