• 19.2.2 [LeetCode 33] Search in Rotated Sorted Array


    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]).

    You are given a target value to search. If found in the array return its index, otherwise return -1.

    You may assume no duplicate exists in the array.

    Your algorithm's runtime complexity must be in the order of O(log n).

    Example 1:

    Input: nums = [4,5,6,7,0,1,2], target = 0
    Output: 4
    

    Example 2:

    Input: nums = [4,5,6,7,0,1,2], target = 3
    Output: -1

    题意

    有序数组截成两段打乱顺序(或者也可能保持原序),以logn的复杂度找数

    题解

     1 class Solution {
     2 public:
     3     int search(vector<int>& nums, int target) {
     4         if (nums.size() <= 0)return -1;
     5         int pivot = nums[0], size = nums.size(), mididx = size, s=0, e=size-1;
     6         if (nums[size - 1] <= pivot) {
     7             int S = 0,E = size - 1;
     8             while (S <= E) {
     9                 int mid = (S + E) / 2;
    10                 if (nums[mid] >= pivot)
    11                     S = mid + 1;
    12                 else
    13                     E = mid - 1;
    14             }
    15             mididx = S;
    16             if (mididx > size - 1)
    17                 mididx = 0;
    18             if (nums[size - 1] >= target) {
    19                 s = mididx, e = max(size - 1,s);
    20             }
    21             else
    22                 s = 0, e = max(mididx - 1,s);
    23         }
    24         while (s < e) {
    25             int mid = (s + e) / 2;
    26             if (nums[mid] < target)
    27                 s = mid + 1;
    28             else
    29                 e = mid;
    30         }
    31         if (s >= size)return -1;
    32         if (nums[s] == target)
    33             return s;
    34         return -1;
    35     }
    36 };
    View Code

    先找从哪开始是分界点,然后再找数

  • 相关阅读:
    双链表 teacherboubleloopnohead
    System.Reflection(温习二)
    在地址栏调试js(小技巧)
    在vs2005中的ReportViewer(RDLC报表)中使用直接打印功能,在vs2005使用ReportViewer2008
    .net的手动编译类方法
    System.Reflection(温习)
    https://imo.im/
    SOA是什么(转)
    ASP.NET的编译方法(转,复习一下)
    动态生成一个继承接口的类
  • 原文地址:https://www.cnblogs.com/yalphait/p/10349317.html
Copyright © 2020-2023  润新知