zoukankan      html  css  js  c++  java
  • 33. Search in Rotated Sorted Array

    description:

    一个数列,不知道在哪翻转了一下,现在给定一个值,如果他在这个翻转后的数列里, return 它对应的 index
    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).
    Note:

    Example:

    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
    

    answer:

    class Solution {
    public:
        int search(vector<int>& nums, int target) {
            int left = 0, right = nums.size() - 1;
            while (left <= right) {
                int mid = left + (right - left) / 2;
                if (nums[mid] == target) return mid;
                if (nums[mid] < nums[right]) {
                     //较之于普通的二分查找,增加了中轴值得判断
                    if (nums[mid] < target && nums[right] >= target) left = mid + 1;
                    else right = mid - 1;
                } else {
                    if (nums[mid] > target && nums[left] <= target) right = mid - 1;
                    else left = mid + 1;
                }
            }
            return -1;
        }
    };
    

    relative point get√:

    hint :

  • 相关阅读:
    P3531 [POI2012]LIT-Letters
    CF1338B Edge Weight Assignment
    CF118C Fancy Number
    New Year Contest
    P2587 [ZJOI2008]泡泡堂
    2021拓维游记
    CF1338C Perfect Triples
    gcc、g++、gdb安装
    vim教程之背键盘使我快乐
    Python起个头
  • 原文地址:https://www.cnblogs.com/forPrometheus-jun/p/11095370.html
Copyright © 2011-2022 走看看