Http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=DSL_3_B
For a given arrayA1,A2,A3,...,ANA1,a2,a3,..., An ofNN elements and an integerKK, find the smallest sub-array size (smallest window length) where the elements in the sub-array contains all integers in range [1 , 2, ... ,k1,2,..., K]. If There is no such sub-array, report 0.
Idea:two pointer. 1.one is left and another are right, start from 0
2.move right pointer first until finding all the elements satisfying the requirements
3.move left (narrowing the subarray) until break the (sum<k)
4.then Move right (repeat 2,3)
5.end with and pointers move to end
ImportJava.util.Scanner; Public classSmallestWindow2 {//Http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=DSL_3_A //http://judge.u-aizu.ac.jp/onlinejudge/review.jsp?rid=2692179#1--Reference Public Static voidMain (string[] args) {Scanner in=NewScanner (system.in); intn =In.nextint (); intK = In.nextint ();//Target intA[] =New int[N+1]; for(inti = 1; I<=n; i++) {A[i]=In.nextint (); } intTag[] =New int[K+1]; //Use pointer intP1 = 0, p2 = 0; intmin = n+1;//Smallest size intsum = 0; //moving the pointer and check the sum < K while(p1<=N) { //P2 = p1; if(sum==K) {min= Math.min (min, p2-p1); //System.out.println (min); } //Main body//Move right Pointer if(sum<K) {P2++; if(p2>n) Break; if(A[P2] <=K) { if(tag[a[p2]]==0) sum++; TAG[A[P2]]++; } }Else{P1++; if(p1>n) Break; if(a[p1]<=K) {TAG[A[P1]]--; if(tag[a[p1]]==0) sum--; } } } if(min = = n+1) SYSTEM.OUT.PRINTLN (0); ElseSystem.out.println (min); }}
Folder:smallest window with the pointers
Similar problems:the folder in AIZU (1-4)
Leetcode problem
.................
Sliding window-the Smallest Window II (AIZU)