Leetcode 81. Search in Rotated Sorted Array II 旋转数组查询2 解题报告

1 解题思想

基本思想和之前的一样,但是因为允许重复,如果出现无法判断的情况(请看代码里 新增的区分 的注释),则需要缩减一个范围继续搜索

具体的请看第一个问题:
Leetcode #33. Search in Rotated Sorted Array 旋转数组查询 解题报告

2 原题

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

3 AC解

public class Solution {
    /** * 这道题和上一道的不同之处,在于这道题可以重复,因此在寻找旋转点的时候要记得区分=的情况 * 在最后二分查找的时候也是有一点点不同*/
    public int findRotateIndex(int[] nums,int start,int end){
        if(start==end)
            return start;
        int mid=(start+end)/2;
        //左边的顺序是正确的,那肯定在右边,注意这是没有重复的
        if(nums[start]<nums[mid]){
            return findRotateIndex(nums,mid,end);
        }
        else if(nums[start] == nums[mid]){  //***新增的区分
            return findRotateIndex(nums,start+1,end);
        }
        else{
            return findRotateIndex(nums,start,mid);
        }
    }

  public boolean bsearch(int[] nums,int start,int end,int target){
      if(start>end){
          return false;
      }
        int mid=(start+end)/2;
        if(target==nums[mid])
            return true;
        if(target<nums[mid]){
            return bsearch(nums,start,mid-1,target);
        }
        else{
            return bsearch(nums,mid+1,end,target);
        }
  }
    public boolean search(int[] nums, int target) {
        int rotated= findRotateIndex(nums,0,nums.length);
        if(rotated==nums.length) rotated--;
        //根据第一个值,就能判断属于哪一份,然后二分查找
        if(nums[0]<target)
            return bsearch(nums,0,rotated,target);
        if(nums[0]==target){ //***新增的区分
            return bsearch(nums,0,rotated,target) || bsearch(nums,rotated,nums.length-1,target);
        }
        else return bsearch(nums,rotated,nums.length-1,target);
    }
}

你可能感兴趣的:(LeetCode,注释,搜索)