https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/description/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. You may assume no duplicate exists in the array.注意,我们要找的最小值,只会在右端,所以如果已经在右端,则挪RIGHT如果在左端,则挪LEFT 往右端的深沟走 time: o(logn) space: o(1)
1 public int findMin(int[] nums) { 2 if (nums ==null || nums.length ==0) return -1 ; 3 int left = 0, right = nums.length -1; 4 while(left + 1 < right){ 5 int mid = left + (right - left)/2 ; 6 if (nums[mid] < nums[right]){ 7 right = mid ; 8 } else{ 9 //first half: left = mid, move to right 10 left = mid ; 11 } 12 } 13 return nums[left]<nums[right]? nums[left] : nums[right] ; 14 }
原文地址:https://www.cnblogs.com/davidnyc/p/8468908.html
时间: 2024-12-09 22:37:22