public class Solution {

```
public List<Integer> topKFrequent(int[] nums, int k) {
ArrayList<Integer> result = new ArrayList<Integer>();
HashMap<Integer, Integer> num = new HashMap<Integer, Integer>(); //used to count the number of each unique element
for (int i =0; i < nums.length; i++){
if (!num.containsKey(nums[i])){
num.put(nums[i], 1);
} else{
num.put(nums[i], num.get(nums[i])+1);
}
}
for (int j = 1; j<=k ;j++){
int max = 0; // the max count number of one element
int val = 0; // the value of the max counted number
for (Map.Entry<Integer, Integer> entry:num.entrySet()){ // search for the max count number
if (max < entry.getValue()){
max = entry.getValue();
val = entry.getKey();
}
}
result.add(val);
num.remove(val);
}
return result;
}
```

}