已排序的 java 数组中的重复项

Duplicates in a sorted java array(已排序的 java 数组中的重复项)
本文介绍了已排序的 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 数组中的重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

How to send data to COM PORT using JAVA?(如何使用 JAVA 向 COM PORT 发送数据?)
How to make a report page direction to change to quot;rtlquot;?(如何使报表页面方向更改为“rtl?)
Use cyrillic .properties file in eclipse project(在 Eclipse 项目中使用西里尔文 .properties 文件)
Is there any way to detect an RTL language in Java?(有没有办法在 Java 中检测 RTL 语言?)
How to load resource bundle messages from DB in Java?(如何在 Java 中从 DB 加载资源包消息?)
How do I change the default locale settings in Java to make them consistent?(如何更改 Java 中的默认语言环境设置以使其保持一致?)