zoukankan      html  css  js  c++  java
  • Leetcode: 81. Search in Rotated Sorted Array II

    Description

    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.

    思路

    • 肯定是个二分
    • 因为是个旋转数组,前一部分比后一部分都大
    • 所以判断中点是落到前一半还是后一半了,若是前一半,然后根据target和mid,low的关系可以给出二分判断
    • 因为数组可以重复,若是mid == low, 则low++,因为此时无法判断去掉哪一边

    代码

    class Solution {
    public:
        bool search(vector<int>& nums, int target) {
            int len = nums.size();
            if(len == 0) return false;
            
            int low = 0, high = len - 1, mid = 0;
            while(low < high){
                mid = low + (high - low) / 2;
                if(nums[mid] == target)
                    return true;
                
                if(nums[mid] > nums[low]){
                    if(nums[mid] < target || nums[low] > target)
                        low = mid + 1;
                    else high = mid - 1;
                }
                else if(nums[mid] < nums[low]){
                    if(target >= nums[low] || target < nums[mid])
                        high = mid - 1;
                    else low = mid + 1;
                }
                else low++;
            }
            
            return target == nums[low];
        }
    };
    
  • 相关阅读:
    Javascript 正确用法 二
    c# 未能载入文件或程序集
    Linux系统备份
    环保创业的可行之道——Leo鉴书上66
    Oracle的序列
    UVA 10574
    网页内容的html标签补全和过滤的两种方法
    使用POI来实现对Excel的读写操作
    OVER(PARTITION BY)函数介绍
    Kill 正在执行的存储过程
  • 原文地址:https://www.cnblogs.com/lengender-12/p/6945111.html
Copyright © 2011-2022 走看看