Tuesday, November 17, 2015

[leetcode]Search Insert Position

记住判断条件是<= 还有结束是return left left+(right-left)/2 是防止overflow
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
public class Solution {
    public int searchInsert(int[] nums, int target) {
        int left = 0;
        int right = nums.length-1;
        while (left <= right){
         int mid =  left+(right-left)/2;
         if (target == nums[mid]){
          return mid;
         }else if(target > nums[mid]){
             left = mid+1;
         }else{
          right = mid-1;
         }
        }
        return left;
    }
}

No comments:

Post a Comment