LeetCode.1438 绝对差不超过限制的最长连续子数组

原题

https://leetcode-cn.com/problems/longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit/
在这里插入图片描述

思路

  • 滑动窗口,右边界一直移动
  • 如果差值小于等于limit时,取最大窗口长度
  • 如果差值大于limit时,移动左边界,直到差值小于limit

题解

package com.leetcode.code;

import java.util.PriorityQueue;
import java.util.Queue;

/**
 * @Description:
 * @ClassName: Code1843
 * @Author: ZK
 * @Date: 2021/2/21 00:17
 * @Version: 1.0
 */
public class Code1843 {

    public static void main(String[] args) {
        int[] nums = {4,2,2,2,4,4,2,2};
        int limit = 0;
        System.out.println(longestSubarray(nums, limit));
    }

    public static int longestSubarray(int[] nums, int limit) {
        int len = nums.length;
        int res = 0;
        int left = 0;
        int right = 0;
        int min = nums[left];
        int max = nums[left];

        for (right = 0; right < len; right++) {
            min = Math.min(min, nums[right]);
            max = Math.max(max, nums[right]);
            if (max-min <= limit) {
                res = Math.max(res, right-left+1);
                continue;
            } else {
//                移动左指针
                while(true) {
                    left++;
                    if (nums[left] == nums[left-1]) {
                        continue;
                    }
                    max = getMax(nums, left, right);
                    min = getMin(nums, left, right);
                    if (max-min <= limit) {
                        res = Math.max(res, right-left+1);
                        break;
                    }
                }
            }
        }

        return res;
    }

    public static int getMax(int[] nums, int start, int end){
        int max = nums[start];
        for (int i = start+1; i <= end; i++) {
            max = Math.max(max, nums[i]);
        }
        return max;
    }

    public static int getMin(int[] nums, int start, int end){
        int min = nums[start];
        for (int i = start+1; i <= end; i++) {
            min = Math.min(min, nums[i]);
        }
        return min;
    }


}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

难过的风景

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值