[LeetCode] Search in Rotated Sorted Array I (33) && II (81) 解题思路

时间:2023-03-09 02:36:57
[LeetCode] Search in Rotated Sorted Array I (33) && II (81) 解题思路

33. Search in Rotated Sorted Array

Suppose a sorted array 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).

You are given a target value to search. If found in the array return its index, otherwise return -1.

You may assume no duplicate exists in the array.

问题: 给定一个已排序的数组,该数组以某一个元素作为支点做了旋转,在改旋转后数组中搜索值。

已排序数组的搜索,自然会想到二分搜索。将旋转到后面的部分用负数表示下标,便可以正常使用二分搜索。

需要注意的是对比元素值 和 目标值时,记得将 下标转会正数 ( i + len ) % len 。

=================================

81. 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.

问题: 若 Search in Rotated Sorted Array 中的数组存在重复元素,如何解决原问题?

重复元素对于上面算法唯一一个影响,就是算法实现时候,判断是否有旋转需要更严谨一点。

第一题代码:

     int search(vector<int>& nums, int target) {

         int len = (int)nums.size();

         if (len == ){
return -;
} if ( len == ){
return (nums[] == target) ? : -;
} int realL;
int realR;
if (nums[] > nums[len-]) {
for ( int i = ; i < len ; i++){
if (nums[i] > nums[i+]){
realR = i;
break;
}
} realL = realR - len + ;
}else{
realL = ;
realR = len - ;
} while( realL < realR ){ if (realL + == realR){
int idxL = ( realL + len ) % len;
int idxR = ( realR + len ) % len; if (nums[idxL] == target){
return idxL;
} if (nums[idxR] == target){
return idxR;
} return -;
} int mid = ( realL + realR ) / ;
int idx = ( mid + len ) % len; if (nums[idx] == target){
return idx;
} if (nums[idx] < target){
realL = mid;
}else{
realR = mid;
}
} // Actually, program will never step to here. It will return value previously.
return -;
}

第二题代码:

    bool search(vector<int>& nums, int target) {

        int len = (int)nums.size();

        if (len == ){
return false;
} if ( len == ){
return (nums[] == target) ? : ;
} int realL;
int realR; int ii = ;
while (ii < len - ) {
if (nums[ii] <= nums[ii + ]) {
ii++;
continue;
}else{
break;
}
} if (ii == len - ) {
realL = ;
realR = len - ;
}else{
realR = ii;
realL = realR - len + ;
} while( realL < realR ){ if (realL + == realR){
int idxL = ( realL + len ) % len;
int idxR = ( realR + len ) % len; if (nums[idxL] == target){
return true;
} if (nums[idxR] == target){
return true;
}
return false;
} int mid = ( realL + realR ) / ;
int idx = ( mid + len ) % len; if (nums[idx] == target){
return true;
} if (nums[idx] < target){
realL = mid;
}else{
realR = mid;
}
} // Actually, program will never step to here. It will return value previously.
return -;
}