2017年4月21日 星期五

[LeetCode] 154. Find Minimum in Rotated Sorted Array II

轉自LeetCode

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++
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
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]
}
}

沒有留言:

張貼留言