标签:style blog http io ar color os sp for
Follow up for "Find Minimum in Rotated Sorted Array":
What if duplicates are allowed?Would this affect the run-time complexity? How and why?
Suppose a sorted array 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.
题意:求一个由不降序的数组转换成的新数组的最小值是多少
思路:第一种方法是:我们可以画出一个不降序的线段,然后有可能在任意点切掉,这个就是断点,所以可以看出出现第一个s[i]<s[i-1]的数的话,那么第i个数就是满足的
class Solution { public: int findMin(vector<int> &num) { if (num.size() == 0) return 0; if (num.size() == 1) return num[0]; for (int i = 1; i < num.size(); i++) if (num[i] < num[i-1]) return num[i]; return num[0]; } };第二种方法是:用vector自带的min_element暴力出来
class Solution { public: int findMin(vector<int> &num) { if (num.size() == 0) return 0; vector<int>::iterator it = min_element(num.begin(), num.end()); return *it; } };
class Solution { public: int findMin(vector<int> &num) { int left = 0; int right = num.size() - 1; while (left < right) { if (num[left] < num[right]) break; int mid = (left + right) / 2; if (num[mid] > num[right]) left = mid + 1; else if (num[left] > num[mid]) right = mid; else left = left + 1; } return num[left]; } };
LeetCode Find Minimum in Rotated Sorted Array II
标签:style blog http io ar color os sp for
原文地址:http://blog.csdn.net/u011345136/article/details/41809679