剑指Offer面试题8 & Leetcode153

剑指Offer面试题8 & Leetcode153

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.

解题思路

  考虑:旋转之后原数组可以分为两部分,并且这两部分分别是递增数组,前一个子数组的元素均大于后一个子数组的元素,可以用二分法查找。如果mid元素大于left元素,则左侧数组为递增数组,最小值位于右侧数组,所以将left赋值为mid继续查找。在循环过程中,left总是指向左侧数组的元素,right总是指向右侧数组的元素。这样,当left和right相邻时,right所指的元素即为最小元素。

Solution

public int findMin(int[] nums) {
        int left = 0;
        int right = nums.length - 1;
        if(nums[left]<=nums[right])     return nums[0];
        int mid;
        while(left != right - 1){
            mid = (left+right)/2;
            if(nums[mid]>nums[left]){
                left = mid;
            }
            if(nums[mid]return nums[right];
    }

你可能感兴趣的:(剑指offer-java实现,leetcode-java)