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;
            }
        }

  

posted @ 2017-12-20 02:49  apanda009  阅读(157)  评论(0编辑  收藏  举报