zoukankan      html  css  js  c++  java
  • 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. 左区间是正常的。 2. 右区间正常。 3. 左边和中间相等, 则说明左边到中间都是相同数字,此时需要判断时候和右边相等,如果不相等则搜索右边,如果相等则需要搜索两边。

    代码:

    class Solution {
    public:
        bool search(int A[], int n, int target) {
            // Start typing your C/C++ solution below
            // DO NOT write int main() function
            int left = 0;
            int right = n-1;
            
            
            while (left<=right){
                
                int mid = (left+right)/2;
                
                if (A[mid] == target) return true;
                
                if (A[left]<A[mid]){//left is normally ordered
                    
                    if (A[left]<=target && target<=A[mid]) right = mid-1;
                    else left = mid+1;
                }
                
                else if (A[mid]<A[left]){//right is normally ordered
                    
                    if (A[mid]<=target && target<=A[right]) left = mid+1;
                    else right = mid -1;
                }
                
                else if (A[left] == A[mid]){//left half is all repeats
                
                        if (A[mid] != A[right]) //If right is diff search it
                           left = mid+1;
                        else{//Else, we have to search both halves
                            
                            int result = search(A+left, mid-left, target);//search left
                            if (result == false) 
                                return search(A+mid, right-mid, target);//search right
                            else return result;
                        }
                }
            }
            
            return false;
        }
    };
    

      

  • 相关阅读:
    2804 最大最小数质因数
    5429 多重背包
    1851 越狱
    Gvim使用
    3622 假期
    4906 删数问题
    2845 排序的代价
    poj 3352
    常用正则表达式汇总
    功能简单例子
  • 原文地址:https://www.cnblogs.com/tanghulu321/p/3055784.html
Copyright © 2011-2022 走看看