判断一个数组里有没有重复的数,数组 int [] arr = {2,9,23,2,90,5,35,3,5};
时间: 2023-08-16 10:05:12 浏览: 33
可以使用哈希表来解决这个问题。遍历数组,将每个数作为键存入哈希表中,如果该数已经存在于哈希表中,则说明数组中有重复的数。
下面是使用Java语言实现的代码示例:
```java
int[] arr = {2,9,23,2,90,5,35,3,5};
Map<Integer, Integer> map = new HashMap<>();
for (int i : arr) {
if (map.containsKey(i)) {
System.out.println("数组中有重复的数:" + i);
break;
} else {
map.put(i, 1);
}
}
```
输出结果为:
```
数组中有重复的数:2
```
注意,这里只输出了重复的第一个数。如果需要输出所有重复的数,可以将重复的数存入一个列表中,最后输出列表即可。
相关问题
c语言如何判断一个数组里的数是否在另一个数组里出现
可以使用两个循环遍历两个数组,对于第一个数组中的每个元素,在第二个数组中查找是否有相同的元素。如果找到了相同的元素,即可判断第一个数组中的元素在第二个数组中出现过。
以下是一个示例代码:
```c
#include <stdio.h>
int main() {
int arr1[] = {1, 2, 3, 4, 5};
int arr2[] = {3, 5, 7, 9, 11};
int length1 = sizeof(arr1) / sizeof(int);
int length2 = sizeof(arr2) / sizeof(int);
for (int i = 0; i < length1; i++) {
int found = 0;
for (int j = 0; j < length2; j++) {
if (arr1[i] == arr2[j]) {
found = 1;
break;
}
}
if (found) {
printf("%d is in the second array.\n", arr1[i]);
} else {
printf("%d is not in the second array.\n", arr1[i]);
}
}
return 0;
}
```
输出结果:
```
1 is not in the second array.
2 is not in the second array.
3 is in the second array.
4 is not in the second array.
5 is in the second array.
```
c语言快速判断一个数组里重复值的个数
在C语言中,可以使用计数排序来快速判断一个数组里重复值的个数。具体步骤如下:
1. 遍历数组,统计每个元素出现的次数。
2. 遍历计数数组,统计出现次数大于1的元素的个数,即为数组中重复值的个数。
以下是使用C语言实现的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
int main() {
int arr[] = {1, 2, 3, 1, 2, 4, 5, 3};
int n = sizeof(arr) / sizeof(arr[0]);
int max = arr[0]; // 找出数组中最大的元素
for (int i = 1; i < n; i++) {
if (arr[i] > max) {
max = arr[i];
}
}
int* count = (int*)calloc(max + 1, sizeof(int)); // 计数数组
for (int i = 0; i < n; i++) {
count[arr[i]]++; // 更新元素出现次数
}
int cnt = 0; // 统计重复值的个数
for (int i = 0; i < max + 1; i++) {
if (count[i] > 1) { // 出现次数大于1
cnt++;
}
}
printf("重复值的个数为:%d\n", cnt); // 输出结果
free(count); // 释放计数数组的空间
return 0;
}
```
输出结果为:
```
重复值的个数为:3
```
以上代码中,使用了calloc函数来动态分配计数数组的空间,并使用free函数释放计数数组的空间。时间复杂度为O(n+k),其中k为数组中不同元素的个数,空间复杂度为O(k)。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)