其他分享
首页 > 其他分享> > 旋转数组的最小数字【记录】

旋转数组的最小数字【记录】

作者:互联网

解法一

package algorithmBasic;

/**
 * @author kegekeqi
 * @version 1.0
 * @date 2021-12-12 18:01
 */
public class RotateArray {
	public int minArray(int[] numbers) {
		if (null == numbers || numbers.length == 0) {
			return 0;
		}
		int low = 0;
		int high = numbers.length - 1;
		while (low < high) {
			int mid = (low + high) / 2;
			if (numbers[mid] < numbers[high]) {
				high = mid;
			} else if (numbers[mid] > numbers[high]) {
				low = mid + 1;
			} else {
				high--;
			}
		}
		return numbers[low];
	}

	public static void main(String[] args) {
		RotateArray array = new RotateArray();
		int[] numbers = {3, 4, 5, 1, 2};
		int minArray = array.minArray(numbers);
		System.out.println(minArray);
	}
}

package algorithmBasic;

/**
 * @author kegekeqi
 * @version 1.0
 * @date 2021-12-12 18:16
 */
public class RotateArray2 {
	public int minInReversingList(int[] arr){
		if(arr==null){
			return -1;
		}
		int leftIndex = 0;
		int rightIndex = arr.length -1;
		int midIndex = leftIndex;
		while(arr[leftIndex]>= arr[rightIndex]){
			if(rightIndex - leftIndex <= 1){
				midIndex = rightIndex;
				break;
			}
			midIndex = (leftIndex+rightIndex)/2;
			if(arr[leftIndex]== arr[rightIndex] && arr[midIndex]== arr[leftIndex]){
				return MinInOrder(arr,leftIndex,rightIndex);
			}
			if(arr[midIndex] >= arr[leftIndex]){
				leftIndex = midIndex;
			}else if(arr[midIndex] < arr[rightIndex]){
				rightIndex = midIndex;
			}
		}
		return arr[midIndex];
	}
	public int MinInOrder(int[] arr,int leftIndex,int rightIndex){
		int result = arr[leftIndex];
		for(int i = leftIndex +1;i<rightIndex;i++){
			if(result> arr[i]){
				result = arr[i];
			}
		}
		return result;
	}
	public static void main(String[] args){
		RotateArray2 test = new RotateArray2();
		int[] arr = {3, 4, 5, 1, 2};
		System.out.println(test.minInReversingList(arr));

	}
}

标签:arr,leftIndex,int,最小,旋转,midIndex,numbers,数组,rightIndex
来源: https://blog.csdn.net/weixin_43206161/article/details/121891308