Java solution 5ms


  • 1
    Z
    public int searchInsert(int[] nums, int target) {
        return binarySearchPosition(nums,target);
    }
    private int binarySearchPosition(int[] input,int element){
    	int low=0;
    	int high = input.length-1;
    	int mid=0;
    	while(low<=high){
    	    mid=(low+high)/2;
    		if (input[mid] == element){
    			return mid;
    		}
    		if(low == high){
    			return input[low] > element ? (low ==0 ? 0 : low) : low+1;
    		}
    		
    		if(input[mid] > element){
    			high = mid-1;
    		}
    		else{
    			low=mid+1;
    		}
    	}
    	return low;
    }

Log in to reply
 

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