Friday, June 24, 2016

35. Search Insert Position

A typical binary search solution. But need to be careful about the boundary.

1:  class Solution {  
2:  public:  
3:    int searchInsert(vector<int>& nums, int target) {  
4:      int lo = 0, hi = nums.size()-1;  
5:      while (lo <= hi) {  
6:        int mid = lo + (hi - lo) / 2;  
7:        if (target == nums[mid]) return mid;  
8:        else if (target > nums[mid]) lo = mid + 1;  
9:        else hi = mid-1;  
10:      }  
11:      return lo;  
12:    }  
13:  };  

No comments:

Post a Comment