在 java 中找出数组中唯一的元素的方法有两种:使用 hashset:创建一个 hashset,遍历数组并将元素添加到 hashset 中。hashset 中剩余的元素即为唯一的元素。使用 hashmap:创建一个 hashmap,键为数组元素,值为出现次数。遍历数组更新计数。值为 1 的键表示唯一的元素。

如何找出数组中唯一的元素
在 Java 中,找出数组中唯一的元素可以使用以下方法:
使用 HashSet
HashSet 是一种集合类型,它不会存储重复元素。我们可以使用以下步骤:
立即学习“”;
- 创建一个 HashSet uniqueElements。
- 遍历数组,并将每个元素添加到 uniqueElements 中。
- 遍历 uniqueElements 中的元素并将其输出或存储在其他数据结构中。
代码示例:
import java.util.HashSet;
import java.util.Set;
public class FindUniqueElements {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5, 1, 2};
// 创建 HashSet
Set<Integer> uniqueElements = new HashSet<>();
// 遍历数组并添加到 HashSet
for (int i : arr) {
uniqueElements.add(i);
}
// 打印唯一元素
for (int element : uniqueElements) {
System.out.print(element + " ");
}
}
}
登录后复制
输出:
3 4 5
登录后复制
时间复杂度:O(n)
使用 HashMap
HashMap 也是一种集合类型,它将存储在一起。我们可以使用以下步骤:
- 创建一个 HashMap elementCounts,其中键为数组元素,值为出现的次数。
- 遍历数组,并为每个元素更新其计数。
- 遍历 elementCounts 中的键,并找出值等于 1 的键(表示唯一的元素)。
代码示例:
import java.util.HashMap;
import java.util.Map;
public class FindUniqueElements {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5, 1, 2};
// 创建 HashMap
Map<Integer, Integer> elementCounts = new HashMap<>();
// 遍历数组并更新计数
for (int i : arr) {
int count = elementCounts.getOrDefault(i, 0);
elementCounts.put(i, count + 1);
}
// 找到唯一的元素
for (Map.Entry<Integer, Integer> entry : elementCounts.entrySet()) {
if (entry.getValue() == 1) {
System.out.println(entry.getKey());
}
}
}
}
登录后复制
输出:
3 4 5
登录后复制
时间复杂度:O(n)
以上就是java怎么找出数组唯一一个的详细内容,更多请关注IDCBABY其它相关文章!
