本文主要是介绍Leetcode103: Search in Rotated Sorted Array II,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
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.
前两种情况跟上篇博客一样,第三种情况是当中间元素等于首部元素时,此时没法判断哪一部分有序,只能将查找区间左边界加1
class Solution {
public:bool search(vector<int>& nums, int target) {int n = nums.size();if(n==0) return false;int l = 0;int r = n-1;while(l<=r){int mid = (l+r)/2;if(nums[mid] == target) return true;else if(nums[l] < nums[mid]){if(nums[l]<=target && target<nums[mid])r = mid-1;elsel = mid+1;}else if(nums[l] > nums[mid]){if(nums[mid]<target && target<=nums[r])l = mid+1;elser = mid-1;}elsel++;}return false;}
};
这篇关于Leetcode103: Search in Rotated Sorted Array II的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!