Leetcode: 81. Search in Rotated Sorted Array II
2017-06-05 15:20
351 查看
Description
Follow up for "Search in Rotated Sorted Array":What if duplicates are allowed?
Would this affect the run-time complexity? How and why?
Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
(i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).
Write a function to determine if a given target is in the array.
The array may contain duplicates.
思路
肯定是个二分因为是个旋转数组,前一部分比后一部分都大
所以判断中点是落到前一半还是后一半了,若是前一半,然后根据target和mid,low的关系可以给出二分判断
因为数组可以重复,若是mid == low, 则low++,因为此时无法判断去掉哪一边
代码
class Solution { public: bool search(vector<int>& nums, int target) { int len = nums.size(); if(len == 0) return false; int low = 0, high = len - 1, mid = 0; while(low < high){ mid = low + (high - low) / 2; if(nums[mid] == target) return true; if(nums[mid] > nums[low]){ if(nums[mid] < target || nums[low] > target) low = mid + 1; else high = mid - 1; } else if(nums[mid] < nums[low]){ if(target >= nums[low] || target < nums[mid]) high = mid - 1; else low = mid + 1; } else low++; } return target == nums[low]; } };
相关文章推荐
- [Leetcode] 81. Search in Rotated Sorted Array II
- LeetCode 81. Search in Rotated Sorted Array II
- [Leetcode 81, Medium] Search in Rotated Sorted Array II
- 【LeetCode】81. Search in Rotated Sorted Array II (2 solutions)
- leetcode 81:Search in Rotated Sorted Array II
- 81. Search in Rotated Sorted Array II Leetcode Python
- 【LEETCODE】81-Search in Rotated Sorted Array II [Python]
- leetcode 81 : Search in Rotated Sorted Array II
- leetCode 81.Search in Rotated Sorted Array II (旋转数组的搜索II) 解题思路和方法
- LeetCode 81 Search in Rotated Sorted Array II
- leetcode[81]Search in Rotated Sorted Array II
- LeetCode(33)(81) Search in Rotated Sorted Array I II
- leetcode_81——Search in Rotated Sorted Array II(二分查找)
- LeetCode81——Search in Rotated Sorted Array II
- [LeetCode]81 Search in Rotated Sorted Array II
- [leetcode] 81.Search in Rotated Sorted Array II
- leetcode || 81、Search in Rotated Sorted Array II
- [leetcode-81]Search in Rotated Sorted Array II(C)
- leetcode 81 :Search in Rotated Sorted Array II
- Leetcode 81. Search in Rotated Sorted Array II