LeetCode每日一题(Longest Turbulent Subarray)

给定一个整数数组,返回其中最大湍流子数组的长度。湍流子数组是指比较符号在相邻元素间翻转的子数组。例如,输入数组 [9,4,2,10,7,8,8,1,9] 的最大湍流子数组为 [9,4,2,10],长度为5。代码实现使用Rust语言,通过遍历数组并判断相邻元素的大小关系来找到符合条件的子数组。

Given an integer array arr, return the length of a maximum size turbulent subarray of arr.

A subarray is turbulent if the comparison sign flips between each adjacent pair of elements in the subarray.

More formally, a subarray [arr[i], arr[i + 1], …, arr[j]] of arr is said to be turbulent if and only if:

For i <= k < j:
arr[k] > arr[k + 1] when k is odd, and
arr[k] < arr[k + 1] when k is even.
Or, for i <= k < j:
arr[k] > arr[k + 1] when k is even, and
arr[k] < arr[k + 1] when k is odd.

Example 1:

Input: arr = [9,4,2,10,7,8,8,1,9]
Output: 5

Explanation:
arr[1] > arr[2] < arr[3] > arr[4] < arr[5]

Example 2:

Input: arr = [4,8,12,16]
Output: 2

Example 3:

Input: arr = [100]
Output: 1

Constraints:

  • 1 <= arr.length <= 4 * 104
  • 0 <= arr[i] <= 109

持续数数, 遇到不符合条件的,就复位计数,继续数


代码实现(Rust):


impl Solution {
    pub fn max_turbulence_size(arr: Vec<i32>) -> i32 {
        if arr.len() < 3 {
            if arr.len() == 2 {
                if arr[0] != arr[1] {
                    return 2;
                }
                return 1;
            } else {
                return arr.len() as i32;
            }
        }
        let mut ans = 0;
        let mut count = 0;
        let mut prev_cmp = '=';
        for w in arr.windows(2) {
            if w[0] == w[1] {
                count = 0;
                prev_cmp = '=';
            } else if w[0] < w[1] {
                if prev_cmp == '>' {
                    count += 1;
                    ans = ans.max(count);
                } else {
                    count = 2;
                    ans = ans.max(count);
                }
                prev_cmp = '<';
            } else if w[0] > w[1] {
                if prev_cmp == '<' {
                    count += 1;
                    ans = ans.max(count);
                } else {
                    count = 2;
                    ans = ans.max(count);
                }
                prev_cmp = '>';
            }
        }
        if ans == 0 { 1 } else { ans }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值