这段代码请帮我翻译成C语言:function countDuplicates(arr) { let countMap = new Map(); let duplicates = 0; // 统计每个元素出现的次数 for (let i = 0; i < arr.length; i++) { let key = arr[i]; let count = countMap.get(key) || 0; countMap.set(key, count + 1); } // 统计重复元素的个数 for (let count of countMap.values()) { if (count > 1) { duplicates++; } } return duplicates;}// 示例用法let arr = [1, 2, 3, 2, 4, 3, 5, 4, 6];let duplicates = countDuplicates(arr);console.log(duplicates); // 输出:3
时间: 2023-03-29 13:02:38 浏览: 95
请帮我翻译这段代码成C语言:
int countDuplicates(int arr[], int length) {
int countMap[length];
int duplicates = ;
// 统计每个元素出现的次数
for (int i = ; i < length; i++) {
int key = arr[i];
int count = countMap[key] ? countMap[key] : ;
countMap[key] = count + 1;
}
// 统计重复元素的个数
for (int i = ; i < length; i++) {
if (countMap[arr[i]] > 1) {
duplicates++;
}
}
return duplicates;
}
// 示例用法
int arr[] = {1, 2, 3, 2, 4, 3, 5, 4, 6};
int length = sizeof(arr) / sizeof(arr[]);
int duplicates = countDuplicates(arr, length);
printf("%d", duplicates); // 输出:3
相关问题
这段代码请帮我翻译成java语言:function countDuplicates(arr) { let countMap = new Map(); let duplicates = 0; // 统计每个元素出现的次数 for (let i = 0; i < arr.length; i++) { let key = arr[i]; let count = countMap.get(key) || 0; countMap.set(key, count + 1); } // 统计重复元素的个数 for (let count of countMap.values()) { if (count > 1) { duplicates++; } } return duplicates;}// 示例用法let arr = [1, 2, 3, 2, 4, 3, 5, 4, 6];let duplicates = countDuplicates(arr);console.log(duplicates); // 输出:3
以下是代码的Java翻译:
```
import java.util.HashMap;
import java.util.Map;
public class Main {
public static int countDuplicates(int[] arr) {
Map<Integer, Integer> countMap = new HashMap<>();
int duplicates = 0;
// 统计每个元素出现的次数
for (int i = 0; i < arr.length; i++) {
int key = arr[i];
int count = countMap.getOrDefault(key, 0);
countMap.put(key, count + 1);
}
// 统计重复元素的个数
for (int count : countMap.values()) {
if (count > 1) {
duplicates++;
}
}
return duplicates;
}
public static void main(String[] args) {
int[] arr = {1, 2, 3, 2, 4, 3, 5, 4, 6};
int duplicates = countDuplicates(arr);
System.out.println(duplicates); // 输出:3
}
}
```
阅读全文