zoukankan      html  css  js  c++  java
  • 19.2.19 [LeetCode 81] Search in Rotated Sorted Array II

    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?
     1 class Solution {
     2 public:
     3     bool search(vector<int>& nums, int target) {
     4         if (nums.empty())return false;
     5         int pivot = nums[0], n = nums.size(), s = 0, e = n - 1;
     6         while (e>=s && nums[e] == pivot)
     7             e--;
     8         if (e < s)return pivot == target;
     9         while (s <= e) {
    10             int mid = (s + e) / 2;
    11             if (nums[mid] >= pivot)
    12                 s = mid + 1;
    13             else
    14                 e = mid - 1;
    15         }
    16         int mididx = e, S, E;
    17         if (pivot > target)
    18             S = mididx + 1, E = n - 1;
    19         else
    20             S = 0, E = mididx;
    21         while (S <= E) {
    22             int mid = (S + E) / 2;
    23             if (nums[mid] < target)
    24                 S = mid + 1;
    25             else if (nums[mid] == target)return true;
    26             else E = mid - 1;
    27         }
    28         return false;
    29     }
    30 };
    View Code
  • 相关阅读:
    【LeetCode】543. 二叉树的直径
    红色的眼睛黑色的心
    WinForm
    Windows地址栏的妙用
    C#
    WPF
    配置Notepad++万能调试
    盗取连接你wifi的人的qq
    Windows去除开始菜单图标背景
    解决Windows下文件无法删除的问题
  • 原文地址:https://www.cnblogs.com/yalphait/p/10399192.html
Copyright © 2011-2022 走看看