• 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;
        }
    };
    

      

  • 相关阅读:
    PTP 接线方式及通讯距离
    串口通信基本概念
    Modbus RTU 通信应用案例
    Modbus 指令
    Modbus RTU新版本指令介绍
    Integer自动装箱和拆箱
    重写hashCode方法,导致内存泄漏
    Dom4j入门
    Java设计模式(9)——观察者模式
    IntelliJ IDEA版本控制——过滤提交文件
  • 原文地址:https://www.cnblogs.com/tanghulu321/p/3055784.html
Copyright © 2020-2023  润新知