Leetcode——153. Find Minimum in Rotated Sorted Array

题目原址

https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/description/

题目描述

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.

Example1:

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

Example2:

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

解题思路

给定一个原来是升序的数组,但是现在这个数组按照某一个未知的点进行旋转了。现在找到这个数组中最小的元素。
本来以为这个题会严格的卡住时间复杂度,但是其实很简单。就是定义两个变量:leftrightleft指向数组的第一个元素,right指向数组的最后一个元素。从前往后遍历,直到找到左边元素小于右边的元素为止就算找到了数组中最小的元素了。

AC代码

class Solution {
    public int findMin(int[] nums) {
        int ret = 0;
        int left = 0, right = nums.length - 1;
        while(left <= right) {
            if(nums[left] > nums[right])
                left ++;
            else{
                return nums[left];
            }
        }
        return ret;        
    }
}

猜你喜欢

转载自blog.csdn.net/xiaojie_570/article/details/80335127
今日推荐