zoukankan      html  css  js  c++  java
  • 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;
                }
            }
    

      

  • 相关阅读:
    CVE-2019-0708
    windows powershell的常用命令
    sqli-lab(8)
    DVWA--CSP Bypass
    认清自己
    sqli-libs(7)
    DVWA--upload
    sqli-labs(6)
    python学习之路(22)
    BZOJ2434:[NOI2011]阿狸的打字机——题解
  • 原文地址:https://www.cnblogs.com/apanda009/p/8070533.html
Copyright © 2011-2022 走看看