Search in rotated sorted array
2018-06-26 本文已影响1人
世界你好
Solution:
In a sorted rotated array, half of the elements must be in a sorted sequence.
So we can compare the element at begin, medium, end to figure out which part is in a sorted sequence. Then we can tell whether the target element is in the sorted half, if not , other half.
Since each time we discard half of the element. the time complexity is O(logN)
time: O(logN), space : O(1)
题意是让你从一个旋转过后的递增序列中寻找给定值,找到返回索引,找不到返回-1,我们在下面这组数据中寻找规律。
1 2 4 5 6 7 0
2 4 5 6 7 0 1
4 5 6 7 0 1 2
5 6 7 0 1 2 4
6 7 0 1 2 4 5
7 0 1 2 4 5 6
由于是旋转一次,所以肯定有一半及以上的序列仍然是具有递增性质的,我们观察到如果中间的数比左面的数大的话,那么左半部分序列是递增的,否则右半部分就是递增的,那么我们就可以确定给定值是否在递增序列中,从而决定取舍哪半边。
https://github.com/Blankj/awesome-java-leetcode/blob/master/note/033/README.md