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

Search in Rotated Sorted Array II

时间:2015-04-29 19:04:56      阅读:111      评论:0      收藏:0      [点我收藏+]

标签:

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.

 

分析:当允许有重复元素出现的时候,那么Search in Rotated Sorted Array中line14:nums[low] <= nums[mid]所能决定的序列就并非单调递增序列,例如[3,1,3,3,3]。在这种情形下,只需将原来的条件拆分为两种情形:

1. nums[low] < nums[mid] 那么之间的序列一定是递增的,代码为Search in Rotated Sorted Array中的line14~17

2. nums[low] == nums[mid] 由于不能够判断数字到底在何处增加、减少,进行low++后观察。因为low++之后nums[low]一定会变大或者保持不变,变大即满足nums[low] > nums[mid],不变则表示已经进入到重复数字区域。

运行时间 11ms

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

 

Search in Rotated Sorted Array II

标签:

原文地址:http://www.cnblogs.com/amazingzoe/p/4466444.html

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