zoukankan      html  css  js  c++  java
  • lintcode: 寻找旋转排序数组中的最小值

     寻找旋转排序数组中的最小值

    假设一个旋转排序的数组其起始位置是未知的(比如0 1 2 4 5 6 7 可能变成是4 5 6 7 0 1 2)。

    你需要找到其中最小的元素。

    你可以假设数组中不存在重复的元素。

    解题

    可以线性查找 ,逆序后的数组 两个升序的数组,前面的数组元素都比后面数组元素大

    数组降序的时候后面的数就是答案了

    class Solution:
        # @param num: a rotated sorted array
        # @return: the minimum number in the array
        def findMin(self, num):
            # write your code here
            if num == None:
                return -1
            if num[0]< num[len(num) - 1]:
                return num[0]
            for i in range(len(num)-1):
                if num[i] > num[i+1]:
                    return num[i+1]
            return -1

    二分法

    先处理了临界情况,在二分的时候不用处理。

    在二分中没有加入判断这个数是否是最小数的情况,由于在结束的时候 low 附件的数一定是最小说,二分的过程是在向最小数靠近 ,下面程序在LeetCode测试通过 

    public class Solution {
        /**
         * @param num: a rotated sorted array
         * @return: the minimum number in the array
         */
        public int findMin(int[] A) {
            // write your code here
        
            if(A == null || A.length == 0)
                return -1;
            int low = 0;
            int high = A.length - 1;
            // 一个元素
            if(A.length == 1)
                return A[low];
            // 已经升序
            if(A[low] < A[high])
                return A[low];
            // 已经降序
            if(A[high -1] > A[high] )
                return A[high];
            // 在中间的情况 
            while(low < high){
                int mid = (low + high)/2;
                if(A[low] < A[mid])
                    low = mid;
                else 
                    high = mid ;
            }
            return Math.min(A[low],A[low+1]);
        }
    
    }
  • 相关阅读:
    LeetCode(287)Find the Duplicate Number
    LeetCode(290) Word Pattern
    LeetCode(205)Isomorphic Strings
    LeetCode(201) Bitwise AND of Numbers Range
    LeetCode(200) Number of Islands
    LeetCode(220) Contains Duplicate III
    LeetCode(219) Contains Duplicate II
    命令行执行Qt程序
    LeetCode(228) Summary Ranges
    redis 的安装和使用记录
  • 原文地址:https://www.cnblogs.com/bbbblog/p/5292597.html
Copyright © 2011-2022 走看看