算法题:寻找峰值

来源:互联网 发布:树莓派 php 编辑:程序博客网 时间:2024/05/22 09:51

你给出一个整数数组(size 为 n),其具有以下特点:

1、相邻位置的数字是不同的

2、A[0] < A[1] 并且 A[n - 2] > A[n - 1]


假定P是峰值的位置则满足 A[P] > A[P-1] 且 A[P] > A[P+1],写一个函数返回数组中所有峰值的位置。


格式:


输入行输入一个整数数组,输出行输出所有数组中的峰值的位置


样例输入


[ 1,2,1,3,4,5,7,6 ]


样例输出


1,6


解答:

遍历查找,算法复杂度O(n)


import java.util.ArrayList;

class Peak
{
    public static void main(String[] argv)
    {
        int[] arr = {1, 2, 1, 3, 4, 5, 7, 6};
        ArrayList<Integer> peak = new ArrayList<Integer>();
        for (int index = 1; index <= arr.length - 2; ) {
            //判断是否峰点
            if (arr[index] > arr[index - 1] && arr[index] > arr[index + 1]) {
                peak.add(index);
                index += 2;
            } else {
                index += 1;
            }
        }
        //输出
        String output = "";
        for (int index : peak) {
            output += index + ",";
        }
        System.out.println(output.substring(0, output.length() - 1));
    }
}
原创粉丝点击