印出陣列中重複前 k 多的數(The Frequent K)

題目:

給一個陣列,
請印出陣列中重複次數最多的前 k 名。

例如:
陣列:[7, 2, 8, 8, 15, 6, 7, 5, 5, 5, 5, 7]

ex1:
input: k = 2;
印出出現前 2 多的數
output: [5, 7]

ex2:
input: k = 3;
印出出現前 3 多的數
output: [5, 7, 8]

解法:
(Java)


public class TheFrenquentK {

public List<Integer> topKFrequent(int[] nums, int k) {

if (nums == null || nums.length == 0 || k <= 0)
return Collections.emptyList();

// 算出每個數字出現的次數,getOrDefault用法請看最後註解
Map<Integer, Integer> countMap = new HashMap<>();
for (int i : nums) {
countMap.put(i, countMap.getOrDefault(i, 0) + 1);
}

// 根據元素出現的次數填入 box,每個 box 的位置都放著一個 List,
// 放著出現次數與索引大小相同的元素(出現 1 次的放一起,出現 2 次的放一起....)
List<Integer>[] box = new List[nums.length + 1];

for (int i : countMap.keySet()) {
// countMap.keySet() 是每一個 key [2, 4, 5, 7, 8] 用 i 帶入
int frequency = countMap.get(i);

if (box[frequency] == null)
box[frequency] = new ArrayList<Integer>();

box[frequency].add(i);

for(int index = 1; index<=box.length -1;index++) {
System.out.println( index + "次 "+ "的有 " +box[index]);
}
}

// 根據出現的次數, 出現多的先進去
List<Integer> result = new ArrayList<>();

for (int i = box.length - 1; i >= 0; i--) {
if (box[i] == null)
continue;

if (result.size() >= k)
break;

result.addAll(box[i]);
}

return result;
}

public static void main(String[] args) {
int[] numbers = { 7, 7, 2, 2, 2, 8, 4, 2, 5 };

int k = 2;

TheFrenquentK ans = new TheFrenquentK();

System.out.println("Answer is " + ans.topKFrequent(numbers, k));
}

}

註解:
getOrDefault用法說明

評論