LeetCode 2765最长交换子数组

题目正文不搬运了,太长了。

题目里的s[m - 1] - s[m - 2] = (-1)m 其实不需要考虑这么多,拿个值diff,每次diff *= -1 即可。
直接数组循环一遍就可以。时间复杂度O(n),空间复杂度O(1)

    public int alternatingSubarray(int[] nums) {
        // res 结果, templen:当前交换子数组的长度,diff:差值
        int res = -1, templen = 1, diff = 1;
        for (int i = 0; i < nums.length - 1;) {
            // 满足交换子数组要求
            if (nums[i + 1] - nums[i] == diff) {
                ++templen;
                diff *= -1;
                ++i;
            } else { // 不满足要求
                // 当前结束的子数组长度不满足,直接跳到下一个值作为子数组的第一个
                if (templen == 1) {
                    ++i;
                } else { // 长度满足,和结果对比,赋值
                    res = res > templen ? res : templen;
                }
                // 重新开始,当前的值可以作为新的子数组的第一个。长度重置1,diff重置1
                templen = 1;
                diff = 1;
                // 一个小优化,如果res长度大于一半,则不会出现比它还长的了。
                if (res > nums.length / 2) {
                    break;
                }
            }
        }
        // 最后对比下,防止因为超出下标限制跳出循环。
        res = templen != 1 && res < templen ?  templen : res;
        return res;
    }

快过年了,脑子都不咋动弹了

你可能感兴趣的:(leetcode,算法)