• 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 :

  • 相关阅读:
    SAP中的文档维护
    SAP日期处理函数汇总(转)
    PR PO通过fm创建时,如何传输增强字段
    html+jQuery简单的利息计算器
    上传项目到github
    Nodejs-毕业设计5-小技巧
    Nodejs-毕业设计4-登录页面
    Nodejs-毕业设计3-路径
    Nodejs-毕业设计2-下载依赖准备工作
    Nodejs-毕业设计1-部署环境
  • 原文地址:https://www.cnblogs.com/forPrometheus-jun/p/11095370.html
Copyright © 2020-2023  润新知