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];
            }
        }
    }
  • 相关阅读:
    jQuery UI draggable+droppable+resizable+selectable+sortable
    jQuery获取Select选择的Text和 Value(转)
    跨终端跨域的存储方案
    innerHTML 的坑
    几种Css前端框架资料
    分享一个前端框架 builive
    为什么要使用CDN?
    AliCDN,盛开在云端的花朵
    java 和 C# 的访问权限
    线程queue 事件event 协程
  • 原文地址:https://www.cnblogs.com/iwangzheng/p/5747627.html
Copyright © 2011-2022 走看看