標籤:style blog color io os ar for 資料 div
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.
難度:80.第一次做這道題比較難想到。參看網上的一些想法,binary search的精髓在於target與mid比了之後可以甩掉一半的元素,順著這個思路想,Rotated array中點兩邊的元素不會都是無序的,一定有一邊是有序的,具體是mid左邊還是右邊,取決於mid元素的值與右邊緣的值孰大孰小。
具體來說,假設數組是A,每次左邊緣為l,右邊緣為r,還有中間位置是m。在每次迭代中,分三種情況:
(1)如果target==A[m],那麼m就是我們要的結果,直接返回;
(2)如果A[m]<A[r],那麼說明從m到r一定是有序的(沒有受到rotate的影響),那麼我們只需要判斷target是不是在m到r之間,如果是則把左邊緣移到m+1,否則就target在另一半,即把右邊緣移到m-1。
(3)如果A[m]>=A[r],那麼說明從l到m一定是有序的,同樣只需要判斷target是否在這個範圍內,相應的移動邊緣即可。
根據以上方法,每次我們都可以切掉一半的資料,所以演算法的時間複雜度是O(logn),空間複雜度是O(1)。
1 public class Solution { 2 public int search(int[] A, int target) { 3 if (A == null || A.length == 0) { 4 return -1; 5 } 6 int l = 0; 7 int r = A.length - 1; 8 while (l <= r) { 9 int mid = (l + r) / 2;10 if (A[mid] == target) return mid; 11 else if (A[mid] < A[r]) {12 if (target>A[mid] && target<=A[r]) {13 l = mid + 1;14 }15 else {16 r = mid - 1;17 }18 }19 else {20 if (target>=A[l] && target<A[mid]) {21 r = mid - 1;22 }23 else {24 l = mid + 1;25 }26 }27 }28 return -1;29 }30 }
Leetcode: Search in Rotated Sorted Array