[LeetCode] Search in Rotated Sorted Array II

本文探讨了含有重复元素的旋转有序数组搜索问题,并提供了一种解决方案。通过定义findPos函数找到旋转点的位置,再使用二分查找bsearch确定目标值是否存在。此方法考虑了数组可能存在的重复元素对复杂度的影响。

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 class Solution {
 2 public:
 3     int findPos(int a[], int left, int right)
 4     {
 5         if (left > right)
 6             return -1;
 7             
 8         int mid = left + (right - left) / 2;
 9         
10         if (a[left] < a[mid])
11         {
12             int pos = findPos(a, mid + 1, right);
13             if (pos == -1)
14                 return left;
15             else
16                 return a[pos] <= a[left] ? pos : left;
17         }
18         else if (a[left] > a[mid])
19         {
20             int pos = findPos(a, left, mid - 1);
21             if (pos == -1)
22                 return mid;
23             else
24                 return a[pos] < a[mid] ? pos : mid;
25         }
26         else
27         {
28             int pos1 = findPos(a, left, mid - 1);
29             int pos2 = findPos(a, mid + 1, right);
30             if (pos1 == -1 && pos2 == -1)
31                 return mid;
32             else if (pos1 == -1)
33                 return a[mid] < a[pos2] ? mid : pos2;
34             else if (pos2 == -1)
35                 return a[mid] <= a[pos1] ? mid : pos1;
36             else
37             {
38                 if (a[pos1] < a[pos2])
39                     return a[mid] <= a[pos1] ? mid : pos1;
40                 else
41                     return a[mid] < a[pos2] ? mid : pos2;
42             }
43         }
44     }
45     
46     bool bsearch(int a[], int left, int right, int key)
47     {
48         if (left > right)
49             return false;
50             
51         int mid = left + (right - left) / 2;
52         
53         if (a[mid] == key)
54             return true;
55         else if (a[mid] < key)
56             return bsearch(a, mid + 1, right, key);
57         else
58             return bsearch(a, left, mid - 1, key);            
59     }
60     
61     bool search(int A[], int n, int target) {
62         // Start typing your C/C++ solution below
63         // DO NOT write int main() function
64         int pos = findPos(A, 0, n - 1);
65         return bsearch(A, 0, pos - 1, target) || bsearch(A, pos, n - 1, target);
66     }
67 };
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值