• 【Leetcode】81. Search in Rotated Sorted Array II


    Question:

    Follow up for "Search in Rotated Sorted Array":
    What if duplicates are allowed?

    Would this affect the run-time complexity? How and why?

    Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.

    (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).

    Write a function to determine if a given target is in the array.

    The array may contain duplicates.

    Tips:

    给定一个数组,该数组是由一个有序的数组经过旋转(即将前面一段数字接到整个数组之后)得到的。判断target是否存在于该数组之中。

    本题为33题升级版本,数组中的数字可以出现重复,如果target存在,返回他的true不存在则返回false。

    思路:

    本题与33提相似,但是由于数组中存在重复数字,可能会出现low high mid三个数字均相等的情况,这时为了跳出相等数字,需要low++或者high--;

    代码:

     public boolean search(int[] nums, int target) {
            if (nums == null)
                return false;
            int low = 0;
            int len = nums.length;
            int high = len - 1;
            while (low <= high) {
                int mid = low + (high - low) / 2;
                if (nums[mid] == target)
                    return true;
                if (nums[low] < nums[mid] || nums[mid]>nums[high]) {
                    if (target < nums[mid] && target >= nums[low]) {
                        high = mid - 1;
                    } else
                        low = mid + 1;
                }else if(nums[mid]<nums[high] || nums[low]>nums[mid]){
                    if(target<=nums[high] && target>nums[mid]){
                        low=mid+1;
                    }else{
                        high=mid-1;
                    }
                }
                else{
                    low++;
                }
            }
            return false;
        }
  • 相关阅读:
    排序总结[3]_线性排序算法
    Spring九问
    DP-最大递增子序列与最大递增子数组; 最大公共子序列与最大公共子数组。
    java 8 新特性
    数据库事务隔离等级
    算法思维方式之二——DP与DFS
    算法思维方式—— 由排列组合想到的
    java Servlet简介
    java hashCode, 引用以及equals().
    java反射简介
  • 原文地址:https://www.cnblogs.com/yumiaomiao/p/8530333.html
Copyright © 2020-2023  润新知