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];
        }
    };
    
  • 相关阅读:
    8.18 二讲背包问题之完全背包
    8.18 动态规划——背包问题之01背包
    8.17 动态规划——书的抄写
    7.25 二分查找模板
    7.19 股票问题
    7.12 枚举-Jam的计数法
    7.12 递归——双色hanoi塔问题
    7.11 NOIP2007普及组第3题 守望者的逃离
    高数之泰勒公式
    数据结构_线性表之链表(1)
  • 原文地址:https://www.cnblogs.com/lengender-12/p/6945111.html
Copyright © 2011-2022 走看看