• 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

    题目要求了时间复杂度要O(logn),明显的要求用二分查找实现。该题的难点在于判断旋转点在mid的左边还是右边,以及后面的高低索引的变化。

     1 int search(int* nums, int numsSize, int target) {
     2     int low=0,high=numsSize-1;
     3     while (low<=high){
     4         int mid=low+(high-low)/2;
     5         if(nums[mid]==target)  
     6             return mid;
     7         //只有两种情况,旋转点在mid左边,旋转点在mid右边
     8         if(nums[mid]<nums[low]){
     9                 // 6,7,0,1,2,3,4   5
    10                 if (target<nums[mid] || target>=nums[low])
    11                     high=mid-1;
    12                 else
    13                     low=mid+1;
    14         }else{
    15                 // 2,3,4,5,6,7,0   1
    16                 if (target>nums[mid] || target<nums[low])
    17                     low=mid+1;
    18                 else
    19                     high=mid-1;
    20             }
    21     }
    22     return -1;
    23 }
  • 相关阅读:
    浅析区间问题
    关于参加信息竞赛
    路爷爷语录
    CentOS-7安装python虚拟环境
    开发笔记(不定时更新)
    Redis有序集合的权重值选择
    数据缓存(Redis)流程设计--思路
    Flask框架之配置日志信息
    Flask框架之一对多关系模型定义
    Flask框架之多对多关系模型类的定义
  • 原文地址:https://www.cnblogs.com/real1587/p/9822669.html
Copyright © 2020-2023  润新知