LeetCode154——寻找旋转排序数组中的最小值 II

版权声明:我的GitHub:https://github.com/617076674。真诚求星! https://blog.csdn.net/qq_41231926/article/details/86353615

我的LeetCode代码仓:https://github.com/617076674/LeetCode

原题链接:https://leetcode-cn.com/problems/find-minimum-in-rotated-sorted-array-ii/description/

题目描述:

知识点:二分查找法

思路一:暴力破解法

本题是LeetCode153——寻找旋转排序数组中的最小值的加强版,但对于暴力破解法而言,和LeetCode153——寻找旋转排序数组中的最小值无任何差别。

时间复杂度是O(n),其中n为数组中的元素个数。空间复杂度是O(1)。

JAVA代码:

public class Solution {
    public int findMin(int[] nums) {
        int result = Integer.MAX_VALUE;
        for (int i = 0; i < nums.length; i++) {
            if(nums[i] < result){
                result = nums[i];
            }
        }
        return result;
    }
}

LeetCode解题报告:

思路二:二分查找法

LeetCode153——寻找旋转排序数组中的最小值的思路二相比,由于本题可能存在重复的元素,我们需要用一个int型变量result来保存当前已得到的数组中的最小值,基本实现和LeetCode153——寻找旋转排序数组中的最小值的思路二相同。

时间复杂度是O(logn),其中n为数组中的元素个数。空间复杂度是O(1)。

JAVA代码:

class Solution {
    public int findMin(int[] nums) {
        int left = 0, right = nums.length - 1;
        int result = Integer.MAX_VALUE;
        while (left < right) {
            if (right - left == 1) {
                return Math.min(result, Math.min(nums[left], nums[right]));
            }
            int mid = left + (right - left) / 2;
            if (nums[left] < nums[right]) {
                return Math.min(result, nums[left]);
            } else if (nums[left] == nums[right]) {
                result = Math.min(result, nums[left]);
                left++;
                right--;
            } else {
                if (nums[left] <= nums[mid]) {
                    left = mid;
                } else {
                    right = mid;
                }
            }
        }
        return Math.min(result, nums[left]);
    }
}

LeetCode解题报告:

猜你喜欢

转载自blog.csdn.net/qq_41231926/article/details/86353615
今日推荐