0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Leetcode 154. Find Minimum in Rotated Sorted Array II

Last updated at Posted at 2022-11-20

154. Find Minimum in Rotated Sorted Array II

アプローチ

1. 二分探索

class Solution {
    public int findMin(int[] nums) {
        if (nums == null || nums.length == 0) {
            return 0;
        }

        int start = 0;
        int end = nums.length - 1;

        if (nums[start] < nums[end]) {
            return nums[start];
        }

        while (start < end) {// not putting <= because the array contains unique elements

            int mid = start + (end - start) / 2;

            if (nums[mid] < nums[end]) {
                end = mid;
                // end を利用
            } else if ( nums[mid] > nums[end] ) {
                // right side is rotated, expecting smallest number between mid + 1 <=  end;
                // 5 6 7 8 9 1 2 3
                start = mid + 1;
            } else {
                // reduce duplicate
                // 5 6 7 8 9 1 1 3
                end--;
            }
        }
        return nums[end];
    }
}

2. ソート

class Solution {
    public int findMin(int[] nums) {
        Arrays.sort(nums);
        return nums[0];
    }
}

3. 全体探索

class Solution {
    public int findMin(int[] nums) {
        int min = Integer.MAX_VALUE;
        for (int num : nums) {
            if (num < min)
                min = num;
        }
        return min;
    }
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?