【LeetCode】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,在递归时需要先去重,再迭代(递归)。

【C++代码】

class Solution {
public:
    bool search(int A[], int n, int key) {
        if (n<=0) return false;
        if (n==1){
            return (A[0]==key) ? true : false;
        }
        
        int low=0, high=n-1;
        while( low<=high ){
    
            if (A[low] < A[high] && ( key < A[low] || key > A[high]) ) {
                 return false;
            }
            
            //if dupilicates, them binary search the duplication
            while (low < high && A[low]==A[high]){
                low++;
            }
    
            int mid = low + (high-low)/2;
            if (A[mid] == key) return true;
    
            //the target in non-rotated array
            if (A[low] < A[mid] && key >= A[low] && key< A[mid]){
                high = mid - 1;
                continue;
            }
            //the target in non-rotated array
            if (A[mid] < A[high] && key > A[mid] && key <= A[high] ){
                low = mid + 1;
                continue;
            }
            //the target in rotated array
            if (A[low] > A[mid] ){
                high = mid - 1;
                continue;
            }
            //the target in rotated array
            if (A[mid] > A[high] ){
                low = mid + 1;
                continue;
            }
            
            //reach here means nothing found.
            low++;
        }
        return false;
    }
};


【简洁Java版】

public class Solution {
    public boolean search(int[] A, int target) {
        int l = 0;
        int r = A.length - 1;
        while (l <= r) {
            while (l < r && A[l] == A[r]) l++;
            int mid = (l + r) / 2;
            if (target == A[mid]) return true;
            if (A[l] <= A[r]) {
                if (target < A[mid]) r = mid - 1;
                else l = mid + 1;
            } else if (A[l] <= A[mid]) {
                if (target < A[l] || target > A[mid]) l = mid + 1;
                else r = mid - 1;
            } else {
                if (target < A[mid] || target > A[r]) r = mid - 1;
                else l = mid + 1;
            }
        }
        return false;
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值