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 };
  • 相关阅读:
    递归(四):组合
    递归(三):排列
    递归(二):正整数的拆分
    Python sum() 函数
    Python pow() 函数
    Python isinstance() 函数
    Python eval() 函数
    Python any() 函数
    阅读笔记1(面试题功能测试-自动化提升效率)
    sql查询(转)
  • 原文地址:https://www.cnblogs.com/guyufei/p/3408347.html
Copyright © 2011-2022 走看看