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

LeetCode Problem 35:Search Insert Position

时间:2014-12-23 20:58:03      阅读:158      评论: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

思路1:直观的想法,遍历数组,一旦当前元素>=target,当前元素的位置即为插入位置,边界问题处理一下即可。时间复杂度:O(n)

 1 class Solution {
 2 public:
 3     int searchInsert(int A[], int n, int target) {
 4 
 5         if(target > A[n-1])
 6             return n;
 7             
 8         else    {        
 9             for(int i = 0; i < n; i++)  {
10                 if(A[i] >= target)
11                     return i;
12             }
13         }
14     }
15 };

 

思路2:由于给定数组为已经排好序的,可以使用二分查找,比较A[mid]与target的大小。时间复杂度:O(logn)

 1 class Solution {
 2 public:
 3     int searchInsert(int A[], int n, int target) {
 4         
 5         int start = 0;
 6         int end = n - 1;
 7         int mid = 0;
 8         
 9         while(end >= start)  {
10             
11             mid = (start + end) / 2;
12             if(target == A[mid])
13                 return mid;
14             else if(target > A[mid])
15                 start = mid + 1;
16             else
17                 end = mid - 1;
18         }
19         
20         if(target > A[mid])
21             return mid + 1;
22         else
23             return mid;
24 
25     }
26 };

 

LeetCode Problem 35:Search Insert Position

标签:

原文地址:http://www.cnblogs.com/fanyabo/p/4180817.html

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