Java Solution O(longN)


  • 0
    J
    public int searchInsert(int[] nums, int target) {
    
        if(target > nums[nums.length-1])
        	return nums.length;
        
        if(target <= nums[0])
        	return 0;
    	
    	int head = 0;
    	int end = nums.length-1;
    	while(head < end){
        	int mid = (head + end) / 2;
        	if(nums[mid] == target)
        		return mid;
        	if(nums[mid]<target){
        		if(nums[mid+1]>target)
        			return mid+1;
        		else
        			head = mid+1;
        	}else{
        		if(nums[mid-1]<target)
        			return mid;
        		else
        			end = mid-1;   	
        	}
    	}
    	return end;
    }

Log in to reply
 

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