题意:在旋转过的有序数组中找到最小数,数组中可能有重复元素
思路:二分,判断是否有相等的元素,主要是二分的时候的一些细节,比如说是有序的还是rotated
代码:
public int findMin(List<Integer> nums) {//solution1 O(log(N)) int min = Integer.MAX_VALUE; int l = 0, r = nums.size()-1,mid; while (l < r){ if(l + 1 == r){ min = Math.min(min, Math.min(nums.get(l),nums.get(r))); return min; } mid = r + (l - r) / 2; if(nums.get(l) == nums.get(r)){//重复数据 l ++; continue; }else if(nums.get(l) < nums.get(r)){ min = nums.get(l); return min; }else { if(nums.get(mid) == nums.get(r)){//表明右边的数据都相等 r = mid; }else if(nums.get(mid) > nums.get(r)){ l = mid; }else if(nums.get(mid) < nums.get(r)){ r = mid; } } } min = Math.min(min, nums.get(l)); return min; }
时间: 2024-10-06 00:01:50