zoukankan      html  css  js  c++  java
  • 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 }
  • 相关阅读:
    1020. Tree Traversals
    1001. A+B Format
    centos 各类无线网卡编译
    vim 详细配置 超全
    深夜复习strcpy函数原型竟然暗藏着这么多玄机
    第一篇博客
    strcat函数使用中出现的问题
    strcpy与strncpy工作方式及其区别
    strcpy与面试官
    linux下多线程编程
  • 原文地址:https://www.cnblogs.com/real1587/p/9822669.html
Copyright © 2011-2022 走看看