classSolution { public: intfindMin(vector<int>& nums){ if (nums.empty()) return0; int n = nums.size(); int res = nums[0]; for (int i=1;i<n;i++) { if (res>nums[i]) res = nums[i]; } return res; } };
classSolution{ public: intfindMin(vector<int>&nums) { if (nums.empty()) return0; int n = nums.size(); int start = 0; int end = n-1; while (end > start) { int mid = start + (end - start) / 2; if (nums[mid] > nums[end]) { /* 中值 > 右值,最小值在右半边,收缩左边界 */ start = mid + 1; /* 因为中值 > 右值,中值肯定不是最小值,左边界可以跨过mid */ } else { /* 明确中值 < 右值,最小值在左半边,收缩右边界 */ end = mid; /* 因为中值 < 右值,中值也可能是最小值,右边界只能取到mid处 */ } } return nums[start]; /* start == end,最小值输出nums[start]或nums[end]均可 */ } }; /* 包含重复元素的情况 class Solution { public: int findMin(vector<int>& nums) { if (nums.empty()) return 0; int n = nums.size(); int start = 0; int end = n-1; while(end > start) { int mid = start + (end-start)/2; if (nums[mid] > nums[end]) { start = mid+1; } else if (nums[mid] < nums[end]) { end = mid; } else { end--; } } return nums[start]; } }; */
Python:
方法一:暴力遍历:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
# -*- coding:utf-8 -*- classSolution: deffindMin(self, nums: List[int]) -> int: n = len(nums) if n==0: return0 res = nums[0] for i inrange (n): if res >nums[i]: res = nums[i] return res
if __name__ == '_ main__': nums = [3,4,5,1,2] res = Solution().findMin(nums) print(res)
# -*- coding:utf-8 -*- classSolution: deffindMin(self, nums: List[int]) -> int: n = len(nums) if n==0: return0 res = nums[0] start = 0 end = n-1 while end>=start: mid = start+(end-start)//2 if nums[mid]>=res: start=mid+1 if nums[mid]<res: end = mid-1 res = min(res,nums[mid]) return res
if __name__ == '_ main__': nums = [3,4,5,1,2] res = Solution().findMin(nums) print(res)