标签:
题目:
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.
Here are few examples.[1,3,5,6]
, 5 → 2[1,3,5,6]
, 2 → 1[1,3,5,6]
, 7 → 4[1,3,5,6]
, 0 → 0
分析:
二分搜索题,找到插入元素的位置,其实就是找到第一个 其值满足>=target 这一条件的位置。
注意如果最后一个元素也不大于的情况。
代码:
1 class Solution { 2 public: 3 int searchInsert(vector<int>& nums, int target) { 4 if (nums.size() == 0) { 5 return -1; 6 } 7 int start = 0, end = nums.size() - 1; 8 while (start + 1 < end) { 9 int mid = start + (end - start) / 2; 10 if (nums[mid] == target) { 11 return mid; 12 } 13 else if (nums[mid] < target) { 14 start = mid; 15 } 16 else { 17 end = mid; 18 } 19 } 20 if (nums[start] >= target) { 21 return start; 22 } 23 if (nums[end] >= target) { 24 return end; 25 } 26 return end + 1; 27 } 28 };
LeetCode35 Search Insert Position
标签:
原文地址:http://www.cnblogs.com/wangxiaobao/p/5800804.html