首页 > 其他 > 详细

[LeetCode] Search in Rotated Sorted Array II

时间:2015-07-19 14:49:12      阅读:99      评论:0      收藏:0      [点我收藏+]

For those who have already solved Search in Rotated Sorted Array, this problem can be solved similarly using codes for that problem and simply adding codes to skip the duplicates.

For Search in Rotated Sorted Array, I post solutions in C/C++/Python here (C and C++ only needs 11 lines).

Now, based on the above codes, you can solve this problem by simply adding two lines to skip duplicates both starting from left and right.

 1 class Solution {
 2 public: 
 3     bool search(vector<int>& nums, int target) {
 4         int l = 0, r = nums.size() - 1;
 5         while (l <= r) {
 6             while (l < r && nums[l] == nums[l + 1]) l++; // skip duplicates from the left
 7             while (r > l && nums[r] == nums[r - 1]) r--; // skip duplicates from the right
 8             int mid = (l + r) / 2;
 9             if (nums[mid] == target) return true; 
10             if (nums[mid] > target) {
11                 if (nums[l] <= target || nums[mid] < nums[l]) r = mid - 1;
12                 else l = mid + 1;
13             }
14             else {
15                 if (nums[l] > target || nums[mid] >= nums[l]) l = mid + 1;
16                 else r = mid - 1;
17             }
18         }
19         return false;
20     }
21 }; 

 

[LeetCode] Search in Rotated Sorted Array II

原文:http://www.cnblogs.com/jcliBlogger/p/4658580.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!