解答2での解き方をする場合、どういうふうに考えたら、Binary Searchで最小値がだせるっていうのが思いつきますでしょうか?
私の場合は、解答1がすぐ思いついてしまって、Binary Searchで解く解答2の解放が頭に思い浮かびませんでした。
もしかしたら、下記の問題で求められているものの理解が足りていないかもしれません。問題の意図汲み取れる方いましたら、その点もご教示いただけませんでしょうか?
Suppose an array of length n sorted in ascending order is rotated between 1 and n times. For example, the array nums = [0,1,2,4,5,6,7] might become:
[4,5,6,7,0,1,2] if it was rotated 4 times.
[0,1,2,4,5,6,7] if it was rotated 7 times.
Notice that rotating an array [a[0], a[1], a[2], ..., a[n-1]] 1 time results in the array [a[n-1], a[0], a[1], a[2], ..., a[n-2]].Given the sorted rotated array nums of unique elements, return the minimum element of this array.
You must write an algorithm that runs in O(log n) time.
153. Find Minimum in Rotated Sorted Array
解答1
python
1class Solution: 2 def findMin(self, nums: List[int]) -> int: 3 return min(nums) # 1
解答2
python
1class Solution: 2 def findMin(self, nums: List[int]) -> int: 3 # [3,4,5,1,2] 4 first, last = 0, len(nums) - 1 5 while first < last: # 0 < 4, 3 < 4, 4<4 6 midpoint = (first + last) // 2 # 2, 3 7 if nums[midpoint] > nums[last]: # 5 > 2, 5 > 2 8 first = midpoint + 1 # 3, 4 9 else: 10 last = midpoint 11 return nums[first] # 1
text
1Input: nums = [3,4,5,1,2] 2Output: 1 3Explanation: The original array was [1,2,3,4,5] rotated 3 times. 4 5Input: nums = [4,5,6,7,0,1,2] 6Output: 0 7Explanation: The original array was [0,1,2,4,5,6,7] and it was rotated 4 times. 8 9Input: nums = [11,13,15,17] 10Output: 11 11Explanation: The original array was [11,13,15,17] and it was rotated 4 times.