poj3320 (尺取法),poj3320取法

來源:互聯網
上載者:User

poj3320 (尺取法),poj3320取法

n個數,求最小區間覆蓋著n個數中所有的不相同的數字。

解題思路:

AC代碼:

import java.util.HashMap;import java.util.HashSet;import java.util.Map;import java.util.Scanner;import java.util.Set;public class Main{/** * @param args */static int n;static Set<Integer> set = new HashSet<Integer>() ; static int a[]=new int[1000000+2];static Map<Integer,Integer> map=new HashMap<Integer, Integer>();public static void main(String[] args) {// TODO Auto-generated method stubScanner scan=new Scanner(System.in);n=scan.nextInt();for(int i = 0 ; i < n ; i++){              set.add(a[i] = scan.nextInt() ) ;          }  int  size = set.size() ;  //計算不同知識點的個數int start = 0 , end = 0 , sum = 0 ;          int res = n ;         for(;;){              while(end < n && sum < size){                  Integer cnt = map.get(a[end]) ;                  if(cnt == null){                      sum++ ;                      map.put(a[end] , 1) ;                  }                  else map.put(a[end] , cnt+1) ;                  end++ ;              }              if(sum < size) break ;               res = Math.min(end - start , res) ;              int cnt = map.get(a[start]) ;               if(cnt == 1){                  map.remove(a[start]) ;                  sum-- ;              }              else map.put(a[start] , cnt-1) ;              start++ ;          }        System.out.println(res) ;}}

  

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.