首页 > 其他 > 详细

[LeetCode]Search Insert Position

时间:2015-09-06 20:03:25      阅读:266      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!