标签:
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