Duplicates in a sorted java array(已排序的 java 数组中的重复项)
问题描述
我必须编写一个方法,该方法接受一个已经按数字顺序排序的整数数组,然后删除所有重复的数字并返回一个仅包含没有重复的数字的数组.然后必须打印出该数组,因此我不能有任何空指针异常.该方法必须在 O(n) 时间内,不能使用向量或散列.这是我到目前为止所拥有的,但它只有前几个数字按顺序排列,没有重复,然后将重复的数字放在数组的后面.我无法创建临时数组,因为它给了我空指针异常.
I have to write a method that takes an array of ints that is already sorted in numerical order then remove all the duplicate numbers and return an array of just the numbers that have no duplicates. That array must then be printed out so I can't have any null pointer exceptions. The method has to be in O(n) time, can't use vectors or hashes. This is what I have so far but it only has the first couple numbers in order without duplicates and then just puts the duplicates in the back of the array. I can't create a temporary array because it gives me null pointer exceptions.
public static int[] noDups(int[] myArray) {
int j = 0;
for (int i = 1; i < myArray.length; i++) {
if (myArray[i] != myArray[j]) {
j++;
myArray[j] = myArray[i];
}
}
return myArray;
}
推荐答案
由于这似乎是作业,我不想给你确切的代码,但这里是做什么:
Since this seems to be homework I don't want to give you the exact code, but here's what to do:
- 对数组进行第一次遍历,看看有多少重复项
- 创建一个新的大小数组(oldSize - 重复)
- 再次遍历数组以将唯一值放入新数组中
由于数组已排序,您只需检查 array[n] == array[n+1].如果不是,那么它不是重复的.检查 n+1 时请注意数组边界.
Since the array is sorted, you can just check if array[n] == array[n+1]. If not, then it isn't a duplicate. Be careful about your array bounds when checking n+1.
因为这涉及到两次运行,它将在 O(2n) -> O(n) 时间内运行.
edit: because this involves two run throughs it will run in O(2n) -> O(n) time.
这篇关于已排序的 java 数组中的重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:已排序的 java 数组中的重复项


- 如何使 JFrame 背景和 JPanel 透明且仅显示图像 2022-01-01
- 将 Java Swing 桌面应用程序国际化的最佳实践是什么? 2022-01-01
- java.lang.IllegalStateException:Bean 名称“类别"的 BindingResult 和普通目标对象都不能用作请求属性 2022-01-01
- 未找到/usr/local/lib 中的库 2022-01-01
- 在 Java 中,如何将 String 转换为 char 或将 char 转换 2022-01-01
- Eclipse 的最佳 XML 编辑器 2022-01-01
- 转换 ldap 日期 2022-01-01
- 如何指定 CORS 的响应标头? 2022-01-01
- 获取数字的最后一位 2022-01-01
- GC_FOR_ALLOC 是否更“严重"?在调查内存使用情况时? 2022-01-01