zoukankan      html  css  js  c++  java
  • leetcode 153. Find Minimum in Rotated Sorted Array



    Suppose a sorted array 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.

    分析:

    这道题给出了一个有序数组,找出数组中最小的元素,其实就是找出第一个小于最后一个元素出现的位置,

    比如题中给出的 4  5 6  0  1  2 ,

    最后一个元素为2,

    只需要找出第一个小于2的元素出现的位置。

    之所以不用第一个元素作为target,因为翻转数组有一种极限情况,那就是完全不翻转,就是0  1  4  5  6  7,

    这种情况下如果用第一个元素作为target就会出错。

    // find the first element that <= targrt, the last element is the target.

    public class Solution {
        // find the first element that <= targrt, the last element is the target.
        public int findMin(int[] nums) {
            if (nums.length == 0){
                return 0;
            }
            int start = 0, end = nums.length;
            int target = nums[nums.length - 1];
            int mid;
            while (start + 1 < end){
                mid = start + (end - start) / 2;
                if (nums[mid] <= target){
                    end = mid;
                }else{
                    start  = mid;
                }
            }
            if (nums[start] <= target){
                return nums[start];
            }else{
                return nums[end];
            }
        }
    }
  • 相关阅读:
    Python学习第151天(Django之多对多)
    Python学习第150天(目前正在做的内容介绍)
    挑战日语学习100天:Day11
    挑战日语学习100天:Day10
    hdu3853 LOOPS 期望dp
    最长公共子串
    基于后缀数组的字符串匹配
    高度数组模板
    Jenkins持续集成自动化测试
    自动化上传文件
  • 原文地址:https://www.cnblogs.com/iwangzheng/p/5747627.html
Copyright © 2011-2022 走看看