• find valley or a mountain


    Given an array will have either a valley or a mountain, only one, not one of each, find out the index of the valley or peak element
    And with one more assumption: array[i - 1] = array[i] + 1 or array[i - 1] = array[i] - 1.
    Example 1: [1,2,3,4,3,2,1] --> return 3 
    Example 2: [6,5,4,3,2,3,4] --> return 4

    我又想到了另一个idea,使用那个assumption可以达到O(1) 复杂度:首先判断isUp or not,仅以isUp为例, 假设A[x] 是最高点,则有:
    A[x] - A[i] = x - i
    A[x] - A[j] = j - x

    由此可以解出 x = 1/ 2 * (A[j] - A[i] + i + j),isdown同理可求

    public int findPeak(int [] A){
    
                boolean isUp = (A[1] > A[0]) ? true : false;
                if (isUp){
                    return (A[A.length - 1] - A[0] + A.length - 1) / 2;
                } else {
                    return (A[0] - A[A.length - 1] + A.length - 1) / 2;
                }
            }
    

      

  • 相关阅读:
    Adb 命令
    python 属性
    python 计时器
    【网易云课堂工作】什么是本能三元组
    functiontools.partial
    源码
    听总结
    线程和死锁
    加入kendall进入计算
    添加K-CORE值进入运算
  • 原文地址:https://www.cnblogs.com/apanda009/p/8070533.html
Copyright © 2020-2023  润新知