题目要求
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.
给定一个数组,它是通过旋转一个有序数组而来,如 0 1 2 4 5 6 7 -> 4 5 6 7 0 1 2.写个函数来判断给定的target在不在数组中。数组中可能有重复出现的数字。
解题思路
- 对于查找有序数组,我们可以通过二分查找实现;
- 此给定的数组是由有序数组旋转而得,因此,可以采取相同的方法将O(N)的查找变为O(logN).
- 跟一般的二分查找一样,设置left和right指向数组的头和尾;
- 当target大于nums[left]时,left++;
- 否则当target小于nums[right]时,right–;
- 否则当target等于nums[left]或nums[right]时,return TRUE;
- 否则(说明target在nums[left]和nums[right]之间,这是不可能的,因为数组的排序是首尾相接的)判定找不到,return false。
代码
class Solution {
public:
bool search(vector<int>& nums, int target) {
int n = nums.size();
if (n == 0){
return false;
}
int left = 0;
int right = n-1;
while (left<=right){
if (target > nums[left]){
left++;
}else if (target < nums[right]){
right--;
}else if (target == nums[left] || target == nums[right]){
return true;
}else{
return false;
}
}
return false;
}
};
结果
273 / 273 test cases passed.
Status: Accepted
Runtime: 8 ms