[leetcode]81. Search in Rotated Sorted Array II旋转过有序数组里找目标值II(有重)

This is a follow up problem to Search in Rotated Sorted Array, where nums may contain duplicates.

思路

该题是[leetcode]33. Search in Rotated Sorted Array旋转过有序数组里找目标值 的followup

唯一区别是加了line24-26的else语句来skip duplicates

代码

 1 class Solution {
 2     public boolean search(int[] nums, int target) {
 3          // corner case
 4         if (nums.length == 0) return false;
 5         // init
 6         int left = 0;
 7         int right = nums.length - 1;
 8 
 9         while (left <= right) {
10             int mid = left + (right - left) / 2;
11             if (nums[mid] == target) return true;
12             else if (nums[mid] < nums[right]) { // right side is sorted
13                 if (target > nums[mid] && target <= nums[right]) {
14                     left = mid + 1;
15                 } else {
16                     right = mid - 1;
17                 }
18             } else if(nums[mid] > nums[right]){ // left side is sorted 
19                 if (target < nums[mid] && target >= nums[left]) {
20                     right = mid - 1;
21                 } else {
22                     left = mid + 1;
23                 }
24             }else{
25                right--; //skip duplicats 
26             }
27         }
28         return false;
29     }   
30 }

猜你喜欢

转载自www.cnblogs.com/liuliu5151/p/9828237.html