• [LeetCode] Search in Rotated 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.

    思路:利用二分查找的思想。

         旋转之后的数组有这样的规律:以题目给出的数组为例,它将原始的有序数组[1,2,3,3,4,5,6,7]分为了两个有序数组[4,5,6,7]和[0,1,2]。且前面的那个有序数组的值全部大于后面的有序数组。

            计算左边和右指针的中值mid。如果该中间元素位于前面的递增子数组,那么它应该大于或者等于第一个指针指向的元素。同样,如果中间元素位于后面的递增子数组,那么它应该小于或者等于第二个指针指向的元素。按照上述的思路,第一个指针总是指向前面齐增数组的元素,而第二个指针总是指向后面递增子数组的元素。 

         时间复杂度O(lgN),空间复杂度O(1)

       注意:此方法的要求与二分查找一样需要,仅适合于线性表的顺序存储结构,不适合于链式存储结构。而且数组的值不允许重复

       相关题目:剑指offer面试题8

    class Solution {
    public:
        int search(vector<int>& nums, int target) {
            if (nums.empty()) return -1;
            
            int start = 0;
            int end = nums.size() - 1;
            
            while (start <= end) {
                int mid = start + (end - start) / 2;
                if (nums[mid] == target) {
                    return mid;
                } else {
                    if (nums[mid] >= nums[start]) {
                        if (target >= nums[start] &&target < nums[mid]) {
                            end = mid - 1;
                        } else {
                            start = mid + 1;
                        }
                    } else {
                        if (target <= nums[end] && target > nums[mid]) {
                            start = mid + 1;
                        } else {
                            end = mid - 1;
                        }
                    }
                }
            }
            
            return -1;
        }
    };
  • 相关阅读:
    HDU 1009 FatMouse' Trade
    python正则表达式
    Python学习week5
    Python学习week4
    Python学习week3
    Python学习week2
    Python学习week1
    生活的艰辛(最小割,最大密度子图)
    最大获利(最小割,最大权闭合图,最大密度子图)
    最大密度子图
  • 原文地址:https://www.cnblogs.com/vincently/p/4122528.html
Copyright © 2020-2023  润新知