LeetCode 33. Search in Rotated Sorted Array(在旋轉有序序列中搜索)
阿新 • • 發佈:2017-07-15
one cheng http ati .com order hal 幫助 列表
題目標簽:Array 題目中給了我們一個旋轉有序序列,讓我們找到target的index。 其實利用最基本的一個一個找過來都可以通過- -, 題目應該說的更明確一點。讓我們利用binary search來搜索。 以往我們利用binary search 來找的話,都是在排序好了的array裏面。但是這一題,array不一定是排序好的。大部分情況都是一個array裏,分2邊,各自都是排序好的,但是中間有一個斷點。我們來看原題中的例子: 0 1 2 4 5 6 7 最原始的時候是有序排列的, 現在開始向左rotate
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
0 1 2 4 5 6 7 這裏就回到了最初的情況
來分析一下,一旦開始rotate, 就變成分開的兩個有序序列,中間有個斷點在移動。因為這個斷點一直在移動,所以不好根據這個變量來判斷。那麽我們來找一個不變量來判斷。
我們看每次中間紅色的點,當這個中間點比最左邊藍色的點大的時候,說明 左邊的這半(包括中間點)一定是有序序列。右邊的話,不確定。
當這個中間的點沒有比左邊點大的時候,那麽說明右邊的有序序列已經移動過來了,並且占據了中間點,那麽右邊的一半(包括中間點)一定是有序序列。
在了解這個規律後,就可以利用binary search來搜索了,binary search就是要判斷,target 在哪一邊,然後繼續走到那一邊裏繼續搜索。這裏我們要通過那一半肯定是有序序列來幫助查找。首先判斷中間點是不是target,不是的話就判斷target是不是在有序序列裏,通過有序序列裏的兩邊來判斷。是的話就繼續跑到有序的那一邊去繼續搜索。如果不是在有序序列裏,那麽就跑到另外一邊裏面去繼續搜索。
Suppose an array sorted in ascending order 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.
題目標簽:Array 題目中給了我們一個旋轉有序序列,讓我們找到target的index。 其實利用最基本的一個一個找過來都可以通過- -, 題目應該說的更明確一點。讓我們利用binary search來搜索。 以往我們利用binary search 來找的話,都是在排序好了的array裏面。但是這一題,array不一定是排序好的。大部分情況都是一個array裏,分2邊,各自都是排序好的,但是中間有一個斷點。我們來看原題中的例子: 0
Java Solution:
Runtime beats 70.31%
完成日期:07/14/2017
關鍵詞:Array
關鍵點:利用Binary Search 結合 rotated sorted array 中必然有一半是有序序列 來搜索
1 public class Solution 2 { 3 public int search(int[] nums, int target) 4 { 5 if(nums == null || nums.length == 0) 6 return -1; 7 8 int left = 0;9 int right = nums.length - 1; 10 11 while(left <= right) 12 { 13 int mid = left + (right - left) / 2; 14 15 if(nums[mid] == target) // if the middle one is target, return mid index 16 return mid; 17 else if(nums[mid] >= nums[left]) // meaning left half is ascending order 18 { 19 if(target >= nums[left] && target < nums[mid]) // if target is in left half 20 right = mid - 1; // move to left half to search 21 else // target is in right half 22 left = mid + 1; // move to right half to search 23 } 24 else // meaning right half is ascending order 25 { 26 if(target > nums[mid] && target <= nums[right]) // if target is in right half 27 left = mid + 1; 28 else // target is in left half 29 right = mid - 1; 30 31 } 32 33 } 34 35 36 return -1; 37 } 38 }
參考資料:
http://www.cnblogs.com/grandyang/p/4325648.html
LeetCode 算法題目列表 - LeetCode Algorithms Questions List
LeetCode 33. Search in Rotated Sorted Array(在旋轉有序序列中搜索)