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;
            }
        }
    };
  • 相关阅读:
    Java POI Word 写文档
    安装SQL Server Management Studio遇到的29506错误
    DataSet中的relation
    如何在Eclipse中配置Tomcat
    button与submit
    redis应用场景
    机器学习实战-KNN(K-近邻算法)详解
    python中的random扩展
    php函数实现文章列表显示的几秒前,几分钟前,几天前等方法
    HTML5的Video标签的属性,方法和事件汇总
  • 原文地址:https://www.cnblogs.com/lysuns/p/4453472.html
Copyright © 2011-2022 走看看