码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode35 Search Insert Position

时间:2016-08-23 21:43:01      阅读:128      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!