浅谈求函数最宽尖峰的Java实现

本文介绍了一种算法,该算法能够从一个严格单调递增或递减的数列中找出最宽的尖峰(即数值高于其左右相邻值的部分),并返回该尖峰的左右底部坐标。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

函数最宽尖峰(函数最宽上升下降区间):

一个数如果比它左右两边的都大,称为一个尖峰。

输入:第一行是数列长度,第二行是一个数字组成的数列,相邻的数字是严格单调递增或者严格单调递减的(相邻的数不相等)。

输出:数列中最宽的尖峰的左、右底部的坐标。若没有尖峰,则返回(-1,-1)。

思路:

len为尖峰左、右底部之间的距离,low为左底部,high为右底部。result[2]纪录最宽的尖峰的左、右底部的坐标

1)遍历数组1 ~ n - 1,判断nums[i]是否为尖峰

2)找到尖峰后,向左循环找到尖峰左底部,纪录其坐标为low(向左单调减,也即nums[low - 1] < nums[low],若不满足单调减,就到了左峰底);同理,向右循环找到尖峰右底部high。求出此尖峰宽度distance = high - low

3)如果len<distance,更新len的大小,并将lowhigh的坐标付给ret数组。

import java.util.*;
public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int[] nums = new int[n];
        sc.nextLine();
        String str = sc.nextLine();
        String[] strs = str.split(" ");
        for (int i = 0; i < n; i++) 
            nums[i] = Integer.parseInt(strs[i]);
	    int result[] = new int[] {-1, -1};  
	    int len = 0;  
	    int low = 0, high = 0;  
	    for (int i = 1; i < n - 1; ++i) {  
	        if (nums[i] > nums[i-1] && nums[i] > nums[i + 1]) {  
	            low = i - 1;  
	            high = i + 1;  
	            while (low >= 1) {  
	                if (nums[low - 1] < nums[low])  
	                    low --;  
	                else   
	                    break;  
	            }  
	            while (high < n - 1) {  
	                if (nums[high] > nums[high + 1] )
	                    high ++;  
	                else   
	                    break;  
	            }  
	            if (high - low > len) {  
	                len = high - low;  
	                result[0] = low;  
	                result[1] = high;  
	            }  
	        }  
	    }    
    	System.out.println(result[0] + " " + result[1]);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值