【拼多多-笔试真题】数组山谷

题目描述:

数组里的山谷是指一个数组A中的连续子数组B满足以下条件:

(1)B.length>=3;

(2)存在满足:0<i<B.length-1并且B[0]>B[1]>…>B[i-1]>B[i]<B[i+1]<…<B[B.length-1];

现给定一个整形数组A,找出数组A里的最长山谷B的长度,如果没有,则输出0.

思想:
  • 分段统计,统计连续上升的个数和连续下降的个数
  • 二者相关即为总的
  • 注意,出现不符合要求(先下降后上升)的情况复位即可
public class test1 {
	public static int longestMoutain(int[] nums) {
		int res = 0, up = 0, down = 0;
		for(int i = 1; i < nums.length; i++) {
			//如果up>0,说明上升过程,然后出现一个下降,那么复位。。连续(先下降再上升)中断
			//或者左右相等,直接复位
			if((up > 0 && nums[i-1] > nums[i]) || nums[i-1] == nums[i])
				up = down = 0;
			//统计连续上升
			if(nums[i-1] < nums[i])
				up++;
			//统计下降
			if(nums[i-1] > nums[i])
				down++;
			//既有上升区间又有下降区间,符合要求,更新res
			if(up > 0 && down > 0 && up + down + 1 > res)
				res = up + down + 1;
		}
		return res;
	}
	public static void main(String[] args) {
		int[] nums = {5,4,3,2,1,2,3,4,5};
		int result = longestMoutain(nums);
		System.out.println(result);
	}
}

//打印结果
9
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值