-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
39a6727
commit 4f0cedd
Showing
1 changed file
with
41 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,41 @@ | ||
package Heap; | ||
|
||
import java.util.*; | ||
public class slidingWindow { | ||
static class pair implements Comparable<pair>{ | ||
int val; | ||
int idx; | ||
pair(int val, int idx){ | ||
this.val=val; | ||
this.idx=idx; | ||
|
||
} | ||
@Override | ||
public int compareTo(pair p2){ | ||
return p2.val-this.val; | ||
} | ||
} | ||
public static void main(String[] args) { | ||
int arr[]={1,3,-1,-3,5,3,6,7}; | ||
int k=3; | ||
int res[]=new int[arr.length-k+1]; | ||
|
||
PriorityQueue<pair>p=new PriorityQueue<>(); | ||
for(int i=0;i<k;i++){ | ||
p.add(new pair(arr[i],i)); | ||
|
||
} | ||
res[0]=p.peek().val; | ||
for(int i=k;i<arr.length;i++){ | ||
while(p.size()>0 && p.peek().idx<=(i-k)){ | ||
p.remove(); | ||
} | ||
p.add(new pair(arr[i],i)); | ||
res[i-k+1]=p.peek().val; | ||
} | ||
for(int i=0;i<res.length;i++){ | ||
System.out.println(res[i]); | ||
} | ||
} | ||
|
||
} |