找出函数的最宽尖峰

今日头条2017校园招聘 技术综合笔试题
描述:按数组的形式给出函数f(x)的取值,即数组A的A[0]元素为f(0)的取值,数组的取值都为整数,函数在每个点都是严格单调递增或者严格单调递减(即A[i-1] != A[i] != A[i+1]),要求找出最宽的先上升后下降的区间(这个区间内函数的值必须先上升到一个点然后下降,区间的上升和下降的长度必须大于0)
1、如果找到符合条件的最大区间输出相应的左右下标(有多个最大区间时,输出最左边的那个)
2、占不到那么输出-1

输入:
n
n长度的整数数组
输出:
区间的范围

样例输入:
10
1 3 1 2 5 4 3 1 9 10
样例输出:
2 7

思路:
先找到函数的各个阶段的最高点,然后依次寻找最高点左边的最低点theMin,最高点右边的最低点theSecondMin,然后比较各个最高点左右最低点的距离width,找到最大的width,输出两边的下标

代码:

import java.util.Scanner;

public class FunctionMaxWidth {
    public static void findMaxWidth(int[] A){
        int theMin = 0;
        int theSecondMin = 0;
        int width = 0;
        int[] result = {-1,-1};
        for (int i = 1; i < A.length-1; i++) {
            if(A[i-1] < A[i] && A[i] > A[i+1]){
                theSecondMin = i+1;
                theMin = i-1;
                while(theMin > 0){
                    if(A[theMin-1] < A[theMin])
                        theMin--;
                    else
                        break;
                }
                while(theSecondMin < A.length-1){
                    if(A[theSecondMin] > A[theSecondMin+1])
                        theSecondMin++;
                    else
                        break;
                }
                if(theSecondMin - theMin > width){
                    width = theSecondMin - theMin;
                    result[0] = theMin;
                    result[1] = theSecondMin;
                }   
            }
        }
        System.out.println(result[0]+" "+result[1]);
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();
        Scanner scanner2 = new Scanner(System.in);
        String[] str = scanner2.nextLine().split(" ");
        int[] A = new int[n];
        for (int i = 0; i < n; i++) {
            A[i] = Integer.valueOf(str[i]);
        }
        findMaxWidth(A);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值