南大高级算法之备考题——按数值个数排序

题意:按照数字出现的个数从大到小排列,个数相同的按照数值升序排列。

题解:自定义一个数据结构保存数值和数值个数,覆写Arrays.sort(,new Comparator(){});使得先按照数值个数大小判断,再按数值大小判断。

import java.util.*;

class Node{
	public Node(int value){	
		this.value = value;
	}
	int value;
	int count;
	public void getCount(int count){
		this.count = count;
	}
}

public class Main {
    public static void main(String[] args) {
    	Scanner scan = new Scanner(System.in);
		int e_num = scan.nextInt();//测试数
		while(e_num>0){
			int length = scan.nextInt();//the length of array
			HashMap<Integer,Integer> map = new HashMap<>();
			Node[] nodearray = new Node[length];
			for(int i=0;i<length;i++){
				int temp = scan.nextInt();
				nodearray[i] = new Node(temp);
				if(map.containsKey(temp)){
					map.put(temp, map.get(temp)+1);
				}else{
					map.put(temp, 1);
				}
			}
			for(int i=0;i<length;i++){
				nodearray[i].getCount(map.get(nodearray[i].value)); 
			//	System.out.println(nodearray[i].count);
			}
			Arrays.sort(nodearray,new Comparator<Node>(){
				@Override
				public int compare(Node o1,Node o2){
					if(o1.count>o2.count){
						return -1;	
					}
					if(o1.count<o2.count){
						return 1;	
					}
					if(o1.value<o2.value){
						return -1;	
					}
					if(o1.value>o2.value){
						return 1;	
					}
					return 0;	
				}
			});
			for(int i=0;i<length;i ++){
				if(i!=length-1){
					System.out.print(nodearray[i].value+" ");
				}else{
					System.out.print(nodearray[i].value);
				}
			}
			System.out.println();
			e_num --;
		}
    }
}
发布了36 篇原创文章 · 获赞 2 · 访问量 1975

猜你喜欢

转载自blog.csdn.net/fumonster/article/details/103356705