zoukankan      html  css  js  c++  java
  • Search in Rotated Sorted Array II [LeetCode]

    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.

    Summary: Almost the same to Search in Rotated Sorted Array without duplicates, but careful about the corner case like [1311], we should search both left half and right half. So, in this case, the run-time complexity will between O(logN) to O(N).

     1 class Solution {
     2 public:
     3     bool search(int A[], int n, int target) {
     4         if(n == 0)
     5             return false;
     6         if(n == 1) {
     7             if(A[0] == target )
     8                 return true;
     9             else 
    10                 return false;
    11         }
    12         
    13         int median = n/2;
    14         if(A[median] == target)
    15             return true;
    16         if(A[0] == target)
    17             return true;
    18             
    19         if(A[0] < A[median] && target > A[0] && target < A[median] || 
    20             (A[0] > A[median] && (target > A[0] || target < A[median]))){
    21               return search(A + 1, median - 0, target);  
    22             }else if(A[0] == A[median]){
    23                 bool ret1 = search(A + 1, median - 0, target);      
    24                 bool ret2 = false;
    25                 if(n - median - 1 <= 0)
    26                     ret2 = false;
    27                 
    28                 ret2 = search(A + median + 1, n - median -1, target);
    29                 return ret1 || ret2;
    30             }else{
    31                 if(n - median - 1 <= 0)
    32                     return false;
    33                 
    34                 return search(A + median + 1, n - median -1, target);
    35             }
    36     }
    37 };
  • 相关阅读:
    CF687D Dividing Kingdom II
    图论——EK算法
    P6082 [JSOI2015]salesman
    联合权值——树上问题2014noip
    P2071 座位安排——二分图最大匹配
    匈牙利优化时间戳的正确性
    P1541 乌龟棋——线性动规
    P1858 多人背包
    P3558 [POI2013]BAJ-Bytecomputer——线性动归
    P2303 [SDOI2012] Longge 的问题
  • 原文地址:https://www.cnblogs.com/guyufei/p/3408347.html
Copyright © 2011-2022 走看看