Search Insert Position
Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.
You may assume no duplicates in the array.
Example 1:
Input: [1,3,5,6], 5 Output: 2
Example 2:
Input: [1,3,5,6], 2 Output: 1
Example 3:
Input: [1,3,5,6], 7 Output: 4
Example 1:
Input: [1,3,5,6], 0 Output: 0
对于二分查找,真的可以说的是个人可能就有十种不同写法,先贴上我自己的:
1 class Solution { 2 public: 3 int searchInsert(vector<int>& nums, int target) { 4 5 int lo = 0, hi = nums.size() - 1; 6 7 while (lo <= hi) 8 { 9 int mid = lo + (hi - lo) / 2; 10 if (nums[mid] < target) 11 { 12 lo = mid + 1; 13 } 14 else if (nums[mid] > target) 15 { 16 hi = mid - 1; 17 } 18 else 19 { 20 return mid; 21 } 22 23 } 24 25 return lo; 26 } 27 };
再贴一个discuss的,里面有解释,可以仔细品味:
1 class Solution { 2 public: 3 int searchInsert(vector<int>& nums, int target) { 4 int low = 0, high = nums.size()-1; 5 6 // Invariant: the desired index is between [low, high+1] 7 while (low <= high) { 8 int mid = low + (high-low)/2; 9 10 if (nums[mid] < target) 11 low = mid+1; 12 else 13 high = mid-1; 14 } 15 16 // (1) At this point, low > high. That is, low >= high+1 17 // (2) From the invariant, we know that the index is between [low, high+1], so low <= high+1. Follwing from (1), now we know low == high+1. 18 // (3) Following from (2), the index is between [low, high+1] = [low, low], which means that low is the desired index 19 // Therefore, we return low as the answer. You can also return high+1 as the result, since low == high+1 20 return low; 21 } 22 };