zoukankan      html  css  js  c++  java
  • leetcode problem 33 -- 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.

    思路:

      给你一个已排序好但移位了的数组,找到特定的数。画一幅图就很容易理解了。一个被旋转的有序数组A[1..n],假定转折点是A[k],那么A[k+1] < A[k+2] < ... < A[n] < A[1] < A[2] < ... < A[k]

      可以用二分查找稍微改点型:虽然我们不知道转折点k在哪,但是我们还是可以通过比较A[mid]与A[start],A[end]来确定要找的目标书target是在A[start,...,mid]中,还是在A[mid+1,...,end]  所以时间复杂度还是lg(n)

    代码:

    Runtime: 12 ms

    class Solution{
    public:
        int search(int A[], int n, int target) {
            if (n <= 0)
                return -1;
            if (n == 1)
                return *A == target ? 0 : -1;
    
            int begin = 0, end = n, mid = (begin + end) / 2;
    
            if (A[begin] <= A[mid-1]) {
                if (target >= A[begin] && target <= A[mid-1]) {
                    auto it = lower_bound(A, A + mid, target);
                    if (*it == target)
                        return it - A;
                    else 
                        return -1;
                }
                int res = search(A + mid, end - mid, target);
                return res == -1 ? -1 : mid + res;
            }
            else {
                if (target >= A[mid] && target <= A[end-1]) {
                    auto it = lower_bound(A+mid, A+end, target);
                    if (*it == target)
                        return it - A;
                    else
                        return -1;
                }    
                int res = search(A + begin, mid - begin, target);
                return res == -1 ? -1 : begin + res;
            }
        }
    };
  • 相关阅读:
    idea双击打不开没反应的解决办法
    Golang Learn Log #0
    获取请求header的各种方法
    Linux 指令
    Windows下Anaconda的安装和简单使用
    如何把Python脚本导出为exe程序
    C++星号的含义
    仓库盘点功能-ThinkPHP_学习随笔
    详解html中的元老级元素:“table”
    IE在开发工具启动的情况下(打开F12)时 JS才能执行
  • 原文地址:https://www.cnblogs.com/lysuns/p/4453472.html
Copyright © 2011-2022 走看看