滑动窗口解决一些连续数组问题
1.给你一串含有c个正整数的数组, 想让你帮忙求出有多少个下标的连续区间, 它们的和大于等于x。
3 6
2 4 7
输出4
//因为有连续这个条件我们可以用滑动窗口的思想,只需要O(n)的时间复杂度 public long solve(long[] a,long m) { int n=a.length; long cursum=0; //i是窗口左边界,j是窗口右边界 long res=0; for(int i=0,j=0;i<n&&j<=n;cursum-=a[i++]) { while(cursum<m&&j<n) { cursum+=a[j++]; } //如果当前累加大于等于m了,所以可以直接加上后面连续的数都是大于m的 if(cursum>=m) res+=n-j+1;//加1是加自己 //这一波计算完以后,拿走左左边的数 } return res; }
2.找出所有和为S的连续正数序列
public ArrayList<ArrayList<Integer> > FindContinuousSequence(int sum) { //存放结果 ArrayList<ArrayList<Integer> > result = new ArrayList<>(); //两个起点,相当于动态窗口的两边,根据其窗口内的值的和来确定窗口的位置和大小 int plow = 1,phigh = 2; while(phigh > plow){ //由于是连续的,差为1的一个序列,那么求和公式是(a0+an)*n/2 int cur = (phigh + plow) * (phigh - plow + 1) / 2; //相等,那么就将窗口范围的所有数添加进结果集 if(cur == sum){ ArrayList<Integer> list = new ArrayList<>(); for(int i=plow;i<=phigh;i++){ list.add(i); } result.add(list); plow++; //如果当前窗口内的值之和小于sum,那么右边窗口右移一下 }else if(cur < sum){ phigh++; }else{ //如果当前窗口内的值之和大于sum,那么左边窗口右移一下 plow++; } } return result; }
3.找出一个无序数组中两个数和为sum的序列,先排序,然后前后指针,从头部和尾部逐渐移动,时间复杂度O(n*logn)
public ArrayList<ArrayList<Integer> > Find2Sum(int a[],int sum) { //存放结果 ArrayList<ArrayList<Integer> > result = new ArrayList<>(); //两个起点,相当于动态窗口的两边,根据其窗口内的值的和来确定窗口的位置和大小 int plow = 0,phigh = a.length-1; int cur=0; while(phigh > plow){ cur=a[plow]+a[phigh]; if(cur == sum){ ArrayList<Integer> list = new ArrayList<>(); list.add(a[plow]); list.add(a[phigh]); result.add(list); phigh--; //如果当前窗口内的值之和小于sum,那么右边窗口右移一下 }else if(cur < sum){ plow++; }else{ //如果当前窗口内的值之和大于sum,那么左边窗口右移一下 phigh--; } } return result; }
4.找出一个无序数组中三个数和为sum的序列,先排序,找一个标志位位,然后前后指针,从头部和尾部逐渐移动,时间复杂度O(n^2)
public ArrayList<ArrayList<Integer> > Find3Sum(int a[],int sum) { //存放结果 ArrayList<ArrayList<Integer> > result = new ArrayList<>(); //两个起点,相当于动态窗口的两边,根据其窗口内的值的和来确定窗口的位置和大小 int cur=0; for(int i=0;i<a.length-2;i++) { int plow = i+1,phigh = a.length-1; while(phigh > plow){ cur=a[i]+a[plow]+a[phigh];//a[i]是一定要加的 if(cur == sum){ ArrayList<Integer> list = new ArrayList<>(); list.add(a[i]); list.add(a[plow]); list.add(a[phigh]); result.add(list); phigh--; //如果当前窗口内的值之和小于sum,那么右边窗口右移一下 }else if(cur < sum){ plow++; }else{ //如果当前窗口内的值之和大于sum,那么左边窗口右移一下 phigh--; } } } return result; }
四个数,尝试两个标志位,加两个for循环
本文来自博客园,作者:LeeJuly,转载请注明原文链接:https://www.cnblogs.com/peterleee/p/11423557.html