首页 > 其他 > 详细

LeetCode35 Search Insert Position

时间:2016-08-23 21:40:28      阅读:182      评论:0      收藏:0      [点我收藏+]

题目:

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!