There is an integer array nums
sorted in ascending order (with distinct values).
Prior to being passed to your function, nums
is possibly rotated at an unknown pivot index k
(1 <= k < nums.length
) such that the resulting array is [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]]
(0-indexed). For example, [0,1,2,4,5,6,7]
might be rotated at pivot index 3
and become [4,5,6,7,0,1,2]
.
Given the array nums
after the possible rotation and an integer target
, return the index of target
if it is in nums
, or -1
if it is not in nums
.
You must write an algorithm with O(log n)
runtime complexity.
Example 1:
Input: nums = [4,5,6,7,0,1,2], target = 0 Output: 4
Example 2:
Input: nums = [4,5,6,7,0,1,2], target = 3 Output: -1
Example 3:
Input: nums = [1], target = 0 Output: -1
Constraints:
1 <= nums.length <= 5000
-104 <= nums[i] <= 104
- All values of
nums
are unique. nums
is an ascending array that is possibly rotated.-104 <= target <= 104
SOL:
這是一題我就算看了解法,還是不想面對現實的兩步驟解題。(參考GeeksforGeeks,也可以不用兩步驟解的樣子,但好複雜我頭好痛,懶得想了QQ)
要考慮的情況比較多,我花了兩天才寫出來。
Step 1. 用 binary search 找出 pivot 。
ascending order 的 array,通常都會比下一個數字還小,除非他是pivot,才會比下一個還大。
Step 2. 找出pivot後,會有 nums[:pivot+1], nums[pivot+1:] 這兩個 ascending order 的 subarray,判斷 target 在一哪個 subarray中。再用 binary search 找出答案。
若 target 不超過 nums 的最後一個數 (nums[-1]),就代表 target 在 nums[pivot+1:] 的 subarray中。
若 target 比較大,則在前面的 subarray中。
簡單來講是這樣,但是有很多細節。
在 Step 1. findPivot 這個函式中,必須將沒有旋轉的情況列入考慮。
找出pivot後,因為python的sublist的index寫法是包含左邊,不包含右邊。所以nums[:pivot+1]會包含index[0,pivot+1)。
一開始我沒注意到,直接寫nums[:pivot]。因此當 pivot index = 0,nums[:pivot]=nums[0,0)=[ ],會是空的,因此當然找不到。
在判斷 target 應該在哪邊的時候,一開始會想說用最小值nums[pivot+1]來判斷,但試了之後會發現全部的人都會比nums[pivot+1]大,因此後來才用nums[-1]來判斷(第12行)。
Reference:
1. LeetCode-33. Search in Rotated Sorted Array
2. Search an element in a sorted and rotated Array | GeeksforGeeks
留言列表