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

 

转载于:https://www.cnblogs.com/guyufei/p/3408347.html

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值