zoukankan      html  css  js  c++  java
  • search in rotated sorted array leetcode

    原题链接

    题意:给你一个目标值,或者返回其在数组中的下标位置,或者返回-1(表示不存在,查找失败)。

    例如 0 1 2 4 5 6 7 可能成为 4 5 6 7 0 1 2.

    思路分析:

      用二分搜索来找到转折点,也就是最小数的位置。对二分搜索要稍作修改,当a[left]<=a[mid],可以肯定a[left...mid]是升序的,那么a[left]是最小的,也可能最小的在a[mid+1...right]中,所以要比较a[left]和min{a[mid+1...right]},同样对于a[left]>a[mid],做相应的处理。

    来看代码:

     1 class Solution {
     2 public:
     3         int findPos(vector<int>& nums,int left,int right){
     4             //if (nums.empty())//多余
     5             //    return -1;
     6             if (left > right||left>=nums.size())//后面这个条件不要,一些测试用例会产生下标越界错误
     7                 return -1;
     8             int mid = (left + right) / 2;
     9             if (nums[left] <= nums[mid])
    10             {
    11                 int pos = findPos(nums, mid + 1, right);
    12                 if (pos == -1)
    13                     return left;
    14                 else
    15                     return nums[left] < nums[pos] ? left : pos;
    16             }
    17             else
    18             {
    19                 int pos = findPos(nums, left, mid - 1);
    20                 if (pos == -1)
    21                     return mid;
    22                 else
    23                     return nums[mid] < nums[pos] ? mid :pos;
    24             }            
    25         }
    26         int bsearch(vector<int>nums, int left, int right, int key)
    27         {
    28             if (left>right)
    29                 return -1;
    30             int mid = (left + right) / 2;
    31             if (nums[mid] == key)
    32                 return mid;
    33             if (nums[mid] < key)
    34                 return bsearch(nums, mid + 1, right, key);
    35             else
    36                 return bsearch(nums, left, mid - 1, key);
    37         }
    38         int search(vector<int>& nums, int target) 
    39         {
    40             int len = nums.size();
    41             int pos = findPos(nums, 0, len);
    42             int index;
    43             if ((index=bsearch(nums, 0, pos - 1,target)) != -1)
    44                 return index;
    45             else return bsearch(nums, pos, len, target);
    46 
    47         }
    48 };
    手里拿着一把锤子,看什么都像钉子,编程界的锤子应该就是算法了吧!
  • 相关阅读:
    Codeforces 787B. Not Afraid
    Codeforces 670D. Magic Powder
    POJ 1979 Red and Black
    T1215:迷宫
    POJ 1163 The Triangle
    洛谷P1219 八皇后
    T1212:LETTERS
    T1317:【例5.2】组合的输出
    洛谷P1706 全排列问题
    codevs 5971 打击犯罪
  • 原文地址:https://www.cnblogs.com/chess/p/5185526.html
Copyright © 2011-2022 走看看