1. 程式人生 > >Jessica's Reading Problem——POJ3320

Jessica's Reading Problem——POJ3320

amp for 統計 sca imp 而且 區間 map() rem

Jessica‘s Reading Problem——POJ3320

題目大意:

Jessica 將面臨考試,她只能臨時抱佛腳的在短時間內將課本內的所有知識點過一輪,課本裏面的P個知識點順序混亂,而且重復。

要求找出課本的連續頁數,這些頁數滿足:包含全部知識點,且是包含全部知識點的頁數區間裏面最短的。

尺取法解題。

import java.util.HashMap;
import java.util.HashSet; 
import java.util.Iterator;
import java.util.Scanner;

public class
Main { public static void main(String[] args) { Scanner reader=new Scanner(System.in); int P=reader.nextInt(); Integer array[]=new Integer[P]; HashSet set=new HashSet(); for(int i=0;i<P;i++){ array[i]=reader.nextInt(); set.add(array[i]); }
int n=set.size(); //知識點個數 int s=0; //開始結點 int e=0; //結束結點 int num=0; //統計目前知識點個數 int res=P; HashMap map=new HashMap(); while(true){ while(e<P && num<n){ if(map.containsKey(array[e])==false){ //尚未包含此知識點
map.put(array[e], 1); //放入此知識點 num++; }else{ Integer newValue=(Integer)map.get(array[e])+1; //舊知識點 map.put(array[e], newValue); } e++; } if(num<n){ break; } res=Math.min(res,e-s); Integer newValue=(Integer)map.get(array[s])-1; map.put(array[s], newValue); if((Integer)map.get(array[s])==0){ //開始結點的知識點數<=1時,減去開始結點後知識個數會減少 map.remove(array[s]); num--; } s++; //開始結點自增 } System.out.print(res); } }

Jessica's Reading Problem——POJ3320