81. Search in Rotated Sorted Array II

Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.

(i.e., [0,0,1,2,2,5,6] might become [2,5,6,0,0,1,2]).

You are given a target value to search. If found in the array return true, otherwise return false.

Example 1:

Input: nums = [2,5,6,0,0,1,2], target = 0
Output: true

Example 2:

Input: nums = [2,5,6,0,0,1,2], target = 3
Output: false

与上一题相比,有重复的, 程序第10行加一个判断即可。
 1 class Solution {
 2     public boolean search(int[] a, int target) {
 3         int n = a.length;
 4         int lo = 0;
 5         int hi = n - 1;
 6         while(lo<=hi){
 7             int mid = lo+(hi-lo)/2;
 8             if(a[mid]== target)
 9                 return true;
10             if(a[lo]==a[mid]) lo++;//越过相等的点
11             
12             else if(a[lo]<a[mid]){//左半边有序
13                 if(a[lo]<=target && target<=a[mid])//目标值在左半边
14                     hi = mid - 1;
15                 else
16                     lo = mid + 1; 
17             }
18             
19             else{//右半边有序
20                 if(a[mid]<=target && target<=a[hi])
21                     lo = mid + 1;
22                 else
23                     hi = mid - 1;
24             }
25         }
26         return false;  
27         
28     }
29 }

猜你喜欢

转载自www.cnblogs.com/zle1992/p/8996267.html
今日推荐