• Search in Rotated Sorted Array


    Suppose a sorted array 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.

    Analyse: Binary search. 

    Runtime: 4ms. 

     1 class Solution {
     2 public:
     3     int findMin(vector<int>& nums) {
     4         if(nums.empty()) return INT_MAX;
     5         
     6         int lowIndex = 0, highIndex = nums.size() - 1;
     7         while(lowIndex < highIndex) {
     8             int midIndex = lowIndex + (highIndex - lowIndex) / 2;
     9             
    10             if(nums[midIndex] > nums[highIndex])
    11                 lowIndex = midIndex + 1;
    12             else
    13                 highIndex = midIndex;
    14         }
    15         return nums[lowIndex];
    16     }
    17 };

    分析:用二分查找法。mid = (low + high) / 2。考虑如下两种情形:

    1. 如果nums[low] <= nums[mid]表示这一段区间是递增的,倘若target的值在两者之间,那么确定上界为mid - 1,否则下界为mid + 1;

    2. 如果nums[low] > nums[mid]表示mid在最大值之后(举例: [4, 5, 6,0, 1, 2, 3]。数字0在6之后)如果target在nums[mid]和nums[high]之间,则可确定下界为mid + 1;否则上界为mid - 1。

    运行时间7ms

     1 class Solution {
     2 public:
     3     int search(vector<int>& nums, int target) {
     4         if(nums.size() == 0) return -1;
     5         if(nums.size() == 1){
     6             if(nums[0] == target) return 0;
     7             else return -1;
     8         }
     9         
    10         int low = 0, high = nums.size()-1;
    11         while(low <= high){
    12             int mid = (low + high) / 2;
    13             if(nums[mid] == target) return mid;
    14             if(nums[low] <= nums[mid]){
    15                 if(nums[low] <= target && target < nums[mid]) high = mid;
    16                 else low = mid + 1;
    17             }
    18             else{
    19                 if(nums[mid] < target && target <= nums[high]) low = mid + 1;
    20                 else high = mid;
    21             }
    22         }
    23         return -1;
    24     }
    25 };
  • 相关阅读:
    Eureka与ZooKeeper 的比较(转)
    springcloud 与分布式系统(转载)
    jvm 分代回收算法通俗理解
    关于JVM调优
    Java常用的数据结构
    mysql数据库引擎(转载)
    java的堆栈通俗理解
    ArrayList 的实现原理
    hashMap 源码解读理解实现原理和hash冲突
    Sklearn库例子——决策树分类
  • 原文地址:https://www.cnblogs.com/amazingzoe/p/4466325.html
Copyright © 2020-2023  润新知