该楼层疑似违规已被系统折叠 隐藏此楼查看此楼
package leetcode;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Scanner;
/**
* Given a non-empty array of integers, return the k most frequent elements.
For example,
Given [1,1,1,2,2,3] ,return 1.
Note:
You may assume k is always valid, 1 ≤ k ≤ number of unique elements.
Your algorithm’s time complexity must be better than O(n log n), where n is the array’s size
* @author Ting
*
*/
public class Main{
public static void main(String[] args) {
List list=new ArrayList();
Scanner sc=new Scanner(System.in);
sc.useDelimiter(",|\n");
while(sc.hasNext()){
System.out.println(sc.nextInt());
//list.add(sc.nextInt());
}
sc.close();
Map map=new HashMap<>();
for(int i:list){
int item=0;
if(map.containsKey(list.get(i))){
item=map.get(i);
item++;
}else{
item=1;
}
map.put(list.get(i), item);
}
MapCompareByValue mcp=new MapCompareByValue();
List> maplist=new ArrayList<>();
Collections.sort(maplist,mcp);
System.out.println(maplist.get(0).getKey());
}
}
class MapCompareByValue implements Comparator>{
@Override
public int compare(Entry o1, Entry o2) {
return o2.getValue()-o1.getValue();
}
}