滑动窗口算法

滑动窗口算法

他解决什么问题?把嵌套查询转换为单循环,降低时间复杂度。
  • 数组

  • 子字符串


数组
  • 如果一个数组A 中间有任意数,求任意数组中子数据组连续的和。
arr[] = {200,330,600};

substring length is:
 k=2

output value :

330+600=930
  • 如果解决上面的问题

通过暴力法可以解决该问题。采用嵌套循环。这里不做实现。实现没什么难度。

滑动窗口的实现

思路:
第一个、第二个、第三个数等等。 他们都是判断连续子数组最大的和。
那么:
第一个 + 第二个 为一个子数组 ,计算出两个数的和存储到临时变量中,然后滑动数组。第二个+第三个数和。。。。。

代码实现 :

package com.concurrent.framework.leetcode;

public class SumArray {

  public int maxSum(int[] arr, int k) {
    int length = arr.length;
    if(length < k) {
      // check array length
      return -1;
    }

    int maxSum = 0;
    // 提取一个子串的和
    for (int i = 0; i < k; i++) {
      maxSum += arr[i];
    }
    
    
    int sum = maxSum;
    for (int i = k; i < length; i++) {
       sum += arr[i]- arr[i-k];
       maxSum = Math.max(maxSum, sum);
    }
    return maxSum;
  }


  public static void main(String[] args) {
    SumArray sumArray = new SumArray();
    int arr[] = {100,200,600};
    int maxSum = sumArray.maxSum(arr, 2);
    System.out.println(maxSum);
  }
}

字符串
应用(限流)
package com.concurrent.framework.leetcode;

import java.util.Iterator;
import java.util.Random;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.stream.IntStream;

/**
 * 滑动窗口的实现
 *
 * 滑动窗口是对计数器方式的改进,增加一个时间粒度的度量单位
 * 把一分钟分成若干等分(6份,每份10秒),
 * 在每一份上设置独立计数器,在 00:00-00:09
 * 之间发生请求计数器累加1.当等分数量越大限流统计就越详细
 *
 */
public class SilderWindow {

  private ConcurrentLinkedQueue<Long> queue = new ConcurrentLinkedQueue<Long>();

    /**
     * 间隔秒数
     */
    private int seconds;

    /**
     * 最大限流
     */
    private int max;

    public SilderWindow(int max, int seconds) {
      this.seconds = seconds;
      this.max = max;

      /**
       * 永续线程执行清理queue 任务
       */
      new Thread(() -> {
        while (true) {
          try {
            // 等待 间隔秒数-1 执行清理操作
            Thread.sleep((seconds - 1) * 1000L);
          } catch (InterruptedException e) {
            e.printStackTrace();
          }
          clean();
        }
      }).start();

    }

    public static void main(String[] args) throws Exception {

      final SilderWindow timeWindow = new SilderWindow(10, 1);

      // 测试3个线程
      IntStream.range(0, 3).forEach((i) -> {
        new Thread(() -> {
          while (true) {
            try {
              Thread.sleep(new Random().nextInt(20) * 100);
            } catch (InterruptedException e) {
              e.printStackTrace();
            }
            timeWindow.take();
          }

        }).start();

      });

    }

    /**
     * 获取令牌,并且添加时间
     */
    public void take() {


      long start = System.currentTimeMillis();
      try {


        int size = sizeOfValid();
        if (size > max) {
          System.err.println("超限");

        }

        // 锁定当前资源
        synchronized (queue) {
          if (sizeOfValid() > max) {
            System.err.println("超限");
            System.err.println("queue中有 " + queue.size() + " 最大数量 " + max);
          }
          this.queue.offer(System.currentTimeMillis());
        }
        System.out.println("queue中有 " + queue.size() + " 最大数量 " + max);
      }finally {

      }
    }


    public int sizeOfValid() {
      Iterator<Long> it = queue.iterator();
      Long ms = System.currentTimeMillis() - seconds * 1000;
      int count = 0;
      while (it.hasNext()) {
        long t = it.next();
        if (t > ms) {
          // 在当前的统计时间范围内
          count++;
        }
      }

      return count;
    }


    /**
     * 清理过期的时间
     */
    public void clean() {
      // 释放队列中的数据
      Long c = System.currentTimeMillis() - seconds * 1000;

      Long tl = null;
      while ((tl = queue.peek()) != null && tl < c) {
        System.out.println("清理数据");
        queue.poll();
      }
    }

}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值