• 81. Search in Rotated Sorted Array II (JAVA)


    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

    Follow up:

    • This is a follow up problem to Search in Rotated Sorted Array, where nums may contain duplicates.
    • Would this affect the run-time complexity? How and why?

    思路:因为有重复元素,所以不能通过之前的方式判断rotate的地方,需要单独考虑nums[mid] == nums[start]以及nums[mid] == nums[end]的情况,这两种情况分别通过start+1和end-1跳过重复元素。

    时间复杂度:在重复元素不多的情况下,并不很影响时间复杂度;担当每次都走的nums[mid] == nums[start]以及nums[mid] == nums[end],那么时间复杂度从O(logn)增至O(n)

    class Solution {
        public boolean search(int[] nums, int target) {
            return binarySearch(nums,target,0,nums.length-1);
        }
        
        public boolean binarySearch(int[] nums, int target, int start, int end){
            if(start > end) return false;
            
            int mid = start + ((end-start)>>1);
            if(nums[mid] == target) return true;
            
            if(nums[mid] < nums[start]){ //rotate in the left part
                if(target >= nums[start] || target < nums[mid]) return binarySearch(nums, target, start, mid-1);
                else return binarySearch(nums, target, mid+1, end);
            }
            else if(nums[mid] > nums[end]){ //rotate in the right part
                if(target > nums[mid] || target <= nums[end]) return binarySearch(nums, target, mid+1, end);
                else return binarySearch(nums, target, start, mid-1);
            }
            else if(nums[mid] == nums[start]){
                return binarySearch(nums, target, start+1, end);
            }
            else if(nums[mid] == nums[end]){
                return binarySearch(nums, target, start, end-1);
            }
            else{
                if(target > nums[mid]) return binarySearch(nums, target, mid+1, end);
                else return binarySearch(nums, target, start, mid-1);
            }
        }
    }
  • 相关阅读:
    Linux系统下使用pwgen生成密码的使用教程
    使用John the ripper工具来尝试破解Linux密码
    把Arch Linux安装到U盘上的具体教程
    Arch Linux安装后的一些初始设置简介
    Linux下的sed命令使用详解
    Ubuntu GNOME 安装日语输入法(收集)
    网页设定固定背景图片(抄袭自百度FM)
    一个不错的flash 模板
    Ubuntu 14.04 LAMP搭建小记
    KindEditor 修改多图片上传显示限制大小和张数
  • 原文地址:https://www.cnblogs.com/qionglouyuyu/p/10936076.html
Copyright © 2020-2023  润新知