Very Concise and Efficient Java solution, using general Binary Search


  • 0
    S
    public int searchInsert(int[] nums, int target) {
    		int lo = 0, hi = nums.length - 1;
    		//if target > all numbers
    		if(nums[hi] < target) return nums.length;
                //general binary search
    		while(lo < hi) {
    			int mid = lo + (hi - lo)/2;
    			if(nums[mid] == target) {
    				return mid;
    			} else if(nums[mid] < target){
    				lo = mid + 1;
    			} else {
    				hi = mid;// take seriously! NOT hi = mid - 1;
    			}
    		}
    		return  lo;
    	}

Log in to reply
 

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