LeetCode:Search in Rotated Sorted Array II

Search in Rotated Sorted Array II




Total Accepted: 64470  Total Submissions: 200961  Difficulty: Medium

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.

Subscribe to see which companies asked this question

Hide Tags
  Array Binary Search
Hide Similar Problems
  (H) Search in Rotated Sorted Array



















思路:

承接上题【Search in Rotated Sorted Array】,当有重复数字时,如:

nums = {2,3,2,2,2};

lo = 0;hi = 4;mid = 2;

由于nums[lo] == nums[mid] == nums[hi],这时变成顺序查找,即:lo++,hi--。


java code:

public class Solution {
    public int search(int[] nums, int target) {
        
        int lo = 0, hi = nums.length-1;
        while(lo <= hi) {
            
            int mid = lo + (hi-lo)/2;
            if(target == nums[mid]) return mid;
            
            if(nums[lo] <= nums[mid]) {
                if(nums[lo] <= target && target <= nums[mid])
                    hi = mid - 1;
                else
                    lo = mid + 1;
            }else{
                if(nums[mid] <= target && target <= nums[hi])
                    lo = mid + 1;
                else
                    hi = mid - 1;
            }
        }
        
        return -1;
    }
}


你可能感兴趣的:(LeetCode,array,search,binary)