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;
        }
    }
    
  • 相关阅读:
    Json 格式 不能加注释
    优雅是的使用Lambda .map函数
    Tomcat-redis-solr-zookeeper启动命令
    今日静态页面集成
    JMS
    freemarker模板引擎技术
    vscode----vue模板--用户代码片段--快捷
    js求总页数:总条数,每页条数
    新建vue项目
    大数据可视化之---echarts地图组件
  • 原文地址:https://www.cnblogs.com/willwuss/p/12431699.html
Copyright © 2011-2022 走看看