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

[LeetCode] Search in Rotated Array II

时间:2014-11-26 13:45:50      阅读:179      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   io   ar   color   sp   for   on   

Follow up for "Search in Rotated Sorted Array":
What if duplicates are allowed?

Would this affect the run-time complexity? How and why?

Write a function to determine if a given target is in the array.

 

思路:真题思路和http://www.cnblogs.com/vincently/p/4122528.html类似。只是如果有重复的话就不能依靠与边界的比较确定递增的序列。例如,[1,3,1,1,1],对于A[m]>=A[l]来说,[l,m]的假设就不成立。但是还是可以观察到,左边子数组的值都要大于等于右边子数组的值。将A[m]>=A[l]拆分为两种情况:A[m]>A[l],则区间[l,m]一定递增;如果 A[m]==A[l]确定不了,那就l++,往下看一步。

时间复杂度改变为O(n),空间复杂度O(1)

 1 class Solution {
 2 public:
 3     bool search(int A[], int n, int target) {
 4         int first = 0, last = n - 1;
 5         while (first <= last) {
 6             const int mid = (first + last) / 2;
 7             if (A[mid] == target) return true;
 8             if (A[first] < A[mid]) {
 9                 if (A[first] <= target && target < A[mid])
10                     last = mid - 1;
11                 else
12                     first = mid + 1;
13             } else if (A[first] > A[mid]){
14                 if (A[mid] < target && target <= A[last])
15                     first = mid + 1;
16                 else 
17                     last = mid - 1;
18             } else {
19                 first++;
20             }
21         }
22         return false;
23     }
24 };

 

[LeetCode] Search in Rotated Array II

标签:style   blog   http   io   ar   color   sp   for   on   

原文地址:http://www.cnblogs.com/vincently/p/4122676.html

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