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 

Compared with the previous question, there are duplicates, and a judgment can be added to the 10th line of the program.
 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]){ // The left half is ordered 
13                  if (a[lo]<=target && target<=a[mid]) // the target value is on the left half 
14                      hi = mid - 1 ;
 15                  else 
16                      lo = mid + 1 ; 
 17              }
 18              
19              else { // order the right half 
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 }

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325316874&siteId=291194637