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

[LeetCode] Search in Rotated Sorted Array II

时间:2015-07-19 14:50:19      阅读:82      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!