Sliding window-the Smallest Window II (AIZU)

Source: Internet
Author: User

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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.