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 ).
Find the minimum element.
The array may contain duplicates.
<Solution>這題是 Find Minimum in Rotated Sorted Array 的衍生題
不難,只改動一個地方
因為現在會有重複的值出現,所以判斷是從 if(nums.front() > nums.back())
變成 if(nums.front() >= nums.back())
code 如下
c++
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public: | |
int findMin(vector<int>& nums) { | |
if(nums.front() >= nums.back()) { | |
//>> rotated | |
for(int i = nums.size() - 1; i >= 1; i--) { | |
if(nums[i-1] > nums[i]) { | |
return nums[i]; | |
} | |
} | |
} | |
//>> not rotated | |
return nums[0]; | |
} | |
}; |
kotlin
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
fun findMin(nums: IntArray): Int { | |
if (nums.first() >= nums.last()) { | |
for (i in nums.lastIndex downTo 1) { | |
if (nums[i-1] > nums[i]) { | |
return nums[i] | |
} | |
} | |
} | |
return nums[0] | |
} | |
} |
沒有留言:
張貼留言