Leetcode BinarySearch 153 154 Find Minimum in Rotated Sorted Array l & ll

153. Find Minimum in Rotated Sorted Array

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.

Example 1:

Input: [3,4,5,1,2]
Output: 1
Example 2:

Input: [4,5,6,7,0,1,2]
Output: 0

solution :

首先利用binary search求得pivot的位置。
题目解法关键在于找到lo和hi以后如何确定pivot
举例:origi_nums = [1,3,5]
nums = [5,1,3] 很明显此时 pivot =1, 首先比较 nums[lo]和nums[hi]的大小,如果nums[lo] < nums[hi]说明整个数组都是顺序正确的,没有pivot,于是给pivot赋值0;反之如果nums[lo] > nums[hi],说明pivot存在,且就在lo和hi之间,于是给pivot赋值hi。

    public int findMin(int[] nums) {
        if (nums == null || nums.length == 0) return -1;
        if (nums.length == 1) return nums[0];
        int lo = 0;
        int hi = nums.length - 1;
        
        // find the pivot
        // [4, 5, 6, 7, | 0, 1, 2]
        while (lo + 1 < hi) {
            int mid = lo + (hi - lo) / 2;
            
            if (nums[mid] > nums[lo]) {
                lo = mid;
            } else if (nums[mid] < nums[lo]) {
                hi = mid;
            }
        }
        
        // (index in sorted array + hi)%nums.length = index in rotated array
        
        int pivot = (nums[lo] > nums[hi]) ? hi:0;
        return nums[pivot];
    }

154. Find Minimum in Rotated Sorted Array II

154题目区别在于数组中允许出现duplicates。
第一次尝试写出来的代码有点问题

class Solution {
    public int findMin(int[] nums) {
        if (nums == null || nums.length == 0) return -1;
        if (nums.length == 1) return nums[0];
        int thres = nums[nums.length - 1];
        
        int lo = 0;
        int hi = nums.length - 1;
        int pivot = 0;
        
        while (lo + 1 < hi) {
            int mid = lo + (hi - lo) / 2;
            if (nums[mid] < thres) {
                hi = mid;
            } else if (nums[mid] > thres) {
                lo = mid;
            } else if (nums[mid] == thres) {
                hi--;
            }
        }
        
        if (nums[lo] >= thres) {
            pivot = hi;
        }
        
        return nums[pivot];
    }
}

solution

class Solution {
  public int findMin(int[] nums) {
    int low = 0, high = nums.length - 1;

    while (low < high) {
      int pivot = low + (high - low) / 2;
      if (nums[pivot] < nums[high])
        high = pivot;
      else if (nums[pivot] > nums[high])
        low = pivot + 1;
      else
        high -= 1;
    }
    return nums[low];
  }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值