Native-binarysearch method


  • 0
    S
    class Solution {
    public:
        int searchInsert(vector<int>& nums, int target) {
    		int middle, low = 0, high = nums.size() - 1;
    		while (low <= high){
    			middle = low + (high - low) / 2;
    			if (nums[middle] < target)
    				low = middle + 1;
    			else if (nums[middle] > target)
    				high = middle - 1;
    			else
    				return middle;
    		}
    
    		if (nums[middle] < target)
    			return middle + 1;
    		else
    			return middle;
    	}
    };

Log in to reply
 

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