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

[LeetCode]Search Insert Position

时间:2015-09-06 20:06:42      阅读:155      评论:0      收藏:0      [点我收藏+]

标签:

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.

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

 

遍历的方法当然能做,但是时间复杂度O(n)。

二分查找可以将时间复杂度降为O(logn)。

 1 class Solution {
 2 public:
 3     int searchInsert(vector<int>& nums, int target) {
 4         if(nums.size()==0 || target<=nums[0]) return 0;
 5         int n = nums.size();
 6         if(target==nums[n-1]) return (n-1);
 7         if(target>nums[n-1]) return n;
 8         int i=0,j=n-1;
 9         while((j-i)!=1)
10         {
11             int temp = (i+j)/2;
12             if(nums[temp]==target) return temp;
13             else if((nums[temp]<target))
14             {
15                 i = temp;
16             }
17             else
18             {
19                 j=temp;
20             }
21         }
22         return (i+1);
23     }
24 };

 

[LeetCode]Search Insert Position

标签:

原文地址:http://www.cnblogs.com/Sean-le/p/4786868.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!