滑动窗口->dd爱框框

1.题目:

2.题解:

2.1为什么用滑动窗口优化:

因为元素都是大于0的

所以:当找到大于等于x的值时,right可以不用返回

两个指针都往后走;因此可以使用滑动窗口优化暴力解法

2.2:滑动窗口具体使用步骤:

1.进窗口:sum += array[right];

2.判断:sum >= x 时出窗口

灵活更新结果(满足结果后) right-left+1<retlen

3.出窗口:sum -= array[left];


图解:


代码:这里注意使用了一个读取模板,不让Scanner输入会超时

java 复制代码
import java.util.*;
import java.io.*;

public class Main {

    public static void main(String[] args) throws IOException {
        
        Read in = new Read();
        int n = in.nextInt(), x = in.nextInt();
        
        int[] array = new int[n+1];//注意下标从1开始
        
        for(int i = 1; i <= n; i++){
            array[i] = in.nextInt();
        }
        
        int left = 1;
        int right = 1;
        int sum = 0;
        
        int retlen = n;
        int retLeft = -1;
        int retRight = -1;
        
        while(right <= n){
            //进窗口
            sum += array[right];
            
            //判断
            while(sum >= x){
                
                //更新结果
                if(right-left+1 < retlen){
                    retLeft = left;
                    retRight = right;
                    retlen = right-left+1;//更新以便于找出最小值
                }
                
                //出窗口
                sum -= array[left++]; 
            }
            
            right++;
        }
        
      System.out.print(retLeft +" " +retRight);
    }
}
    
 class Read // 自定义快速读入
{
    //字符串截取
    StringTokenizer st = new StringTokenizer("");

    //1.字节流->字符流:new InputStreamReader(System.in)
    //2.带内存缓冲区的字符流:BufferedReader

    BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
    String next() throws IOException
    {
        while(!st.hasMoreTokens())
        {
            ///读内存缓冲区里的一行数据:bf.readLine()
            st = new StringTokenizer(bf.readLine());
        }

        //获取每一个截取的字符串
        return st.nextToken();
    }

    //转化为自己想要的类型
    String nextLine() throws IOException
    {
        return bf.readLine();
    }

     int nextInt() throws IOException
    {
        return Integer.parseInt(next());
    }

    long nextLong() throws IOException
    {
        return Long.parseLong(next());
    }

    double nextDouble() throws IOException
    {
        return Double.parseDouble(next());
    }
}
相关推荐
2401_891482172 小时前
多平台UI框架C++开发
开发语言·c++·算法
88号技师2 小时前
2026年3月中科院一区SCI-贝塞尔曲线优化算法Bezier curve-based optimization-附Matlab免费代码
开发语言·算法·matlab·优化算法
t198751282 小时前
三维点云最小二乘拟合MATLAB程序
开发语言·算法·matlab
x_xbx3 小时前
LeetCode:148. 排序链表
算法·leetcode·链表
Darkwanderor3 小时前
三分算法的简单应用
c++·算法·三分法·三分算法
2401_831920743 小时前
分布式系统安全通信
开发语言·c++·算法
WolfGang0073214 小时前
代码随想录算法训练营 Day17 | 二叉树 part07
算法
温九味闻醉4 小时前
关于腾讯广告算法大赛2025项目分析1 - dataset.py
人工智能·算法·机器学习
炽烈小老头4 小时前
【 每天学习一点算法 2026/03/23】数组中的第K个最大元素
学习·算法·排序算法
老鱼说AI4 小时前
大规模并发处理器程序设计(PMPP)讲解(CUDA架构):第四期:计算架构与调度
c语言·深度学习·算法·架构·cuda