zoukankan      html  css  js  c++  java
  • [leetcode] 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.

    解题思路:

    在做过一定面试题的前提下,看到这种在一个与排序有关的数列里找某个数,应该有感觉与二分查找有关。

    然后尝试一下一下可以发现,

    如果数组的中位数大于末尾数,则最小数应该在后半段。

    如果数组的中位数小于末尾数,则最小数应该在前半段或者是中位数。

    代码如下

    public int findMin(int[] num) {
            int low = 0, high = num.length - 1;
            while (low < high && num[low] >= num[high]) {
                int mid = (low + high) / 2;
                if (num[mid] > num[high])
                    low = mid + 1;
                else
                    high = mid;
            }
            return num[low];
        }
  • 相关阅读:
    子网掩码的作用与IP网段的划分
    DHCP服务器
    Anaconda安装、更新第三方包
    time模块的使用
    TensorFlow安装
    机器学习-线性回归
    机器学习
    Pyhton-类(2)
    python-类(1)
    Python-函数
  • 原文地址:https://www.cnblogs.com/fengmangZoo/p/4741183.html
Copyright © 2011-2022 走看看