当前位置:网站首页>Find minimum in rotated sorted array

Find minimum in rotated sorted array

2022-06-23 09:35:00 ruochen

Suppose a sorted array 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.

The sequence is basically in order , Then use binary search . Suppose the sequence is n,s It's the starting subscript ,e Is the last subscript ,m Is the middle element subscript . There are three situations :

ns < ne

nm > ns > ne

nm < ne < ns

situation 1:ns < ne

0 1 2 4 5 6 7

This situation , Go straight back to ns. Because the sequence is ordered , Or just rotate once . If ns < ne, Indicates that there is no rotation . The smallest element is ns.

situation 2:nm > ns > ne

4 5 6 7 0 1 2

    public int findMin(int[] nums) {
        if (nums.length == 1) {
            return nums[0];
        }
        if (nums.length == 2) {
            return Math.min(nums[0], nums[1]);
        }
        int s = 0, e = nums.length - 1;
        int m = (s + e) / 2;
        if (nums[s] < nums[e]) {
            return nums[s];
        }
        if (nums[m] > nums[s]) {
            return findMin(Arrays.copyOfRange(nums, m + 1, e + 1));
        }
        return findMin(Arrays.copyOfRange(nums, s, m + 1));
    }
原网站

版权声明
本文为[ruochen]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/01/202201081604220921.html