首页 > 代码库 > LeetCode "Find Minimum in Rotated Sorted Array"
LeetCode "Find Minimum in Rotated Sorted Array"
There‘s usually a common strategy for "find *" problems - binary search: half the space can be dropped by some rules.
And take care of corner cases.
class Solution { const int INVALID = std::numeric_limits<int>::min();public: int _findMin(vector<int> &num, int s, int e) { if (s == e) return num[s]; if ((s + 1) == e) { return std::min(num[s], num[e]); // assumption on input } int mid = s + ((e - s) >> 1); if (num[s] <= num[mid] && num[mid + 1] <= num[e]) { if (num[mid] < num[mid + 1]) { return num[s]; } else { return num[mid + 1]; } } else if (num[s] <= num[mid]) { return _findMin(num, mid + 1, e); } else { return _findMin(num, s, mid); } return INVALID; } int findMin(vector<int> &num) { size_t len = num.size(); return _findMin(num, 0, len - 1); }};
LeetCode "Find Minimum in Rotated Sorted Array"
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。