>[success] # 統計數組中元素出現次數

1. 解決思路使用**Map 結構**統計每個數字出現的次數
* 圖

2. 解決思路如果已知元素所存在的范圍足夠小可以使用**數組**來作為統計
* 圖 角標對元素,數組存儲是個數(及元素為索引,次數為value)

>[danger] ##### js 實現
~~~
const arr = [3, 2, 2, 5, 6]
// 使用map
function mapCount(arr) {
return arr.reduce((acc, cur) => {
if (!acc[cur]) {
acc[cur] = 0
}
++acc[cur]
return acc
}, {})
}
// 使用數組
function arrCount(arr) {
return arr.reduce((acc, cur) => {
const index = cur - 1
if (!acc[index]) {
acc[index] = 0
}
++acc[index]
return acc
}, [])
}
console.log(mapCount(arr)) // { '2': 2, '3': 1, '5': 1, '6': 1 }
console.log(arrCount(arr)) // [ <1 empty item>, 2, 1, <1 empty item>, 1, 1 ]
~~~
>[danger] ##### java
~~~ java
import java.sql.Array;
import java.util.HashMap;
import java.util.Map;
public class ArrayCount {
// 使用map 計數
public static Map<Integer,Integer> countArrMap(int[] arr){
// 創建一個Map 對象
Map<Integer,Integer> countMap = new HashMap<>();
for(int num:arr){
if(!countMap.containsKey(num)) {
countMap.put(num,0);
}
int count = countMap.get(num);
// compute 對 hashMap 中指定 key 的值進行重新計算
countMap.compute(num,(key,value)-> value+1);
}
return countMap;
}
// 使用數組計數
public static int[] countArrArr(int[] arr){
// 已知最大數為 6 創建數組長度為6
int[] countArr = new int[6];
for(int num:arr){
// 數組角標從0開始因此-1
int index = num - 1;
++ countArr[index];
}
return countArr;
}
public static void main(String args[]){
int[] ls = {3, 2, 2, 5, 6};
Map<Integer,Integer> mapCount = ArrayCount.countArrMap(ls);
int[] arrCount = ArrayCount.countArrArr(ls);
System.out.println(mapCount);
int idx = 0;
for(int item:arrCount){
System.out.print("key:" + ++idx +"-"+"val:"+item);
}
}
}
~~~
- 刷題準備
- 統計數組中元素出現次數
- Leetcode -- 442數組中重復的數據
- leetcode -- 448 找到所有數組中消失的數字
- 字符類似題
- Leetcode -- 1002 查找共用字符
- Leetcode -- 1370上升下降字符串
- 指針類題解
- Leetcode -- 283 移動零
- Leetcode -- 26. 刪除有序數組中的重復項
- Leetcode -- 80. 刪除有序數組中的重復項 II
- Leetcode -- 27. 移除元素
- Leetcode -- 344. 反轉字符串
- Leetcode -- 125 驗證回文串
- Leetcode -- 11 盛最多水的容器
- Leetcode -- 1480. 一維數組的動態和