zoukankan      html  css  js  c++  java
  • Leetcode 978 Longest Turbulent Subarray. (滑动窗口)

    Leetcode 978

    问题描述

    A subarray A[i], A[i+1], ..., A[j] of A is said to be turbulent if and only if:
    
    For i <= k < j, A[k] > A[k+1] when k is odd, and A[k] < A[k+1] when k is even;
    OR, for i <= k < j, A[k] > A[k+1] when k is even, and A[k] < A[k+1] when k is odd.
    
    That is, the subarray is turbulent if the comparison sign flips between each adjacent pair of elements in the subarray.
    
    Return the length of a maximum size turbulent subarray of A.
    

    例子

    Example 1:
    Input: [9,4,2,10,7,8,8,1,9]
    Output: 5
    Explanation: (A[1] > A[2] < A[3] > A[4] < A[5])
    
    Example 2:
    Input: [4,8,12,16]
    Output: 2
    
    Example 3:
    Input: [100]
    Output: 1
    

    方法一

    ** Solution Java **
    ** 4ms, 95.62% **
    ** 43.5MB, 62.50% **
    class Solution {
        public int maxTurbulenceSize(int[] A) {
            int dec = 1, inc = 1, res = 1;
            for (int i = 1; i < A.length; ++i) {
                if (A[i - 1] < A[i]) {
                    inc = dec + 1;
                    dec = 1;
                } else if (A[i] < A[i - 1]){
                    dec = inc + 1;
                    inc = 1;
                } else {
                    inc = 1;
                    dec = 1;
                }
                res = Math.max(res, Math.max(dec, inc));
            }
            return res;
        }
    }
    

    方法二

    ** Solution Java **
    ** 4ms, 95.62% **
    ** 43.2MB, 62.50% **
    class Solution {
        public int maxTurbulenceSize(int[] A) {
            int pre = 0, cur = 0, len = 1, res = 1;
            for (int i = 1; i < A.length; ++i) {
                cur = Integer.compare(A[i], A[i - 1]);
                if (cur * pre == -1) ++len;
                else if (cur == 0) len = 1;
                else len = 2;
                res = Math.max(res, len);
                pre = cur;
            }
            return res;
        }
    }
    
  • 相关阅读:
    redis 数据迁移
    redis
    Redis集群的三种模式
    Golang 协程 (goroutine) 与通道 (channel)
    Python生成器next方法和send方法区别
    python 文件
    Tornado 异步以及非阻塞的I/O
    python 多进程和多线程3 —— asyncio
    利用CSS改变图片颜色的100种方法!
    jquery获取div的位置
  • 原文地址:https://www.cnblogs.com/willwuss/p/12431699.html
Copyright © 2011-2022 走看看