• 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;
            }
        }
    };
  • 相关阅读:
    技术债务墙:一种让技术债务可见并可协商的方法
    墙裂推荐
    shell 脚本通过Webhook 发送消息到微信群
    关于中医的一段对话 [ZZ] -- 思维训练故事
    应用深度神经网络预测学生期末成绩
    Python中的模块引用机制
    批量修改含空格的文件名「Linux」
    Markdown数学公式语法
    批处理修改IP
    FTD团队目录
  • 原文地址:https://www.cnblogs.com/lysuns/p/4453472.html
Copyright © 2020-2023  润新知