常用的方法为:创建新数组,遍历原数组,将每个唯一元素存储在新数组中,时间复杂度为 O(n^2),空间复杂度为 O(n)。使用 Set 接口,将原数组元素添加到 Set 中,从 Set 中检索元素并将其存储在新数组中,时间复杂度为 O(n),空间复杂度为 O(n)。
如何去除 Java 中数组中的重复项
回答:
去除 Java 数组中重复项的常用方法是创建新数组或使用 Set。
详细说明:
立即学习“Java免费学习笔记(深入)”;
1. 创建新数组
2. 使用 Set
示例:
创建新数组:
int[] originalArray = {1, 2, 3, 4, 4, 5}; // 创建新数组,不包含重复项 int[] newArray = new int[originalArray.length]; int uniqueIndex = 0; for (int i = 0; i < originalArray.length; i++) { boolean unique = true; // 检查当前元素是否已存在于新数组中 for (int j = 0; j < uniqueIndex; j++) { if (originalArray[i] == newArray[j]) { unique = false; break; } } // 如果元素是唯一的,则将其添加到新数组中 if (unique) { newArray[uniqueIndex] = originalArray[i]; uniqueIndex++; } } // 调整新数组的大小 newArray = Arrays.copyOf(newArray, uniqueIndex);
使用 Set:
int[] originalArray = {1, 2, 3, 4, 4, 5}; // 创建 Set,不包含重复项 Set<Integer> uniqueSet = new HashSet<>(); // 将原数组元素添加到 Set 中 for (int num : originalArray) { uniqueSet.add(num); } // 从 Set 中检索元素并存储在新数组中 int[] newArray = new int[uniqueSet.size()]; int index = 0; for (int num : uniqueSet) { newArray[index++] = num; }
以上就是java中怎么去除数组中重复的详细内容,更多请关注php中文网其它相关文章!
java怎么学习?java怎么入门?java在哪学?java怎么学才快?不用担心,这里为大家提供了java速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号