Search in Rotated Sorted Array II

旋转有序数组搜索
本文介绍了一个针对含有重复元素的旋转有序数组的搜索算法。通过实现一个公共类Solution,并定义search方法来查找目标值是否存在数组中。该算法考虑了数组旋转且可能包含重复元素的情况,通过不断调整搜索范围直至找到目标值或确认不存在。

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 public class Solution {
 2     //rotated array all is <= 
 3     public boolean search(int[] A, int target) {
 4         if(A.length<=0){return false;}
 5         int start = 0, end = A.length-1;
 6         while(start<=end){
 7             int mid = (start+end)/2;
 8             if(A[mid]==target) return true;
 9             if(A[mid]>A[start]){
10                 if(target>=A[start] && target<=A[mid]){
11                     end = mid-1;
12                 }
13                 else{
14                     start = mid+1;
15                 }
16             }
17             else if(A[mid]<A[start]){
18                 if(target>=A[mid] && target<=A[end]){
19                     start = mid+1;
20                 }
21                 else{
22                     end = mid-1;
23                 }
24             }
25             else{
26                 start ++;
27             }
28         }
29         return false;
30     }
31 }
View Code

 

转载于:https://www.cnblogs.com/krunning/p/3538771.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值