Home  >  Article  >  Java  >  Share an example of java calculation

Share an example of java calculation

零下一度
零下一度Original
2017-07-21 17:25:261267browse

n numbers, find the minimum interval covering all the different numbers in the n numbers.

Solution ideas:

##AC code:

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 stub
		Scanner 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) ;
	}

}

 

The above is the detailed content of Share an example of java calculation. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn