在排序的Java数组复制 [英] Duplicates in a sorted java array

查看:128
本文介绍了在排序的Java数组复制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须写这需要一个已排序的数字顺序int数组然后删除所有重复的号码,并返回只是没有重复的数字数组的方法。然后,该阵列必须被打印出来,所以我不能有任何空指针异常。该方法是在O(n)的时间,不能使用向量或哈希值。这是我迄今为止,但它只有在顺序的第一对夫妇的数字没有重复,然后只把重复的数组的后面。因为它给我空指针异常,我不能创建一个临时数组。

 公共静态INT [] noDups(INT [] myArray的){
    INT J = 0;
    的for(int i = 1; I< myArray.length;我++){
        如果(myarray的[I]!= myArray的研究[J]){
            J ++;
            myarray的研究[J] = myArray的[I]
        }
    }
    返回myArray的;
}


解决方案

由于这似乎是功课,我不想给你确切的code,但这里做什么:


  • 请第一次运行通过数组的,看看有多少重复的有

  • 创建大小的新阵列(oldSize - 重复)

  • 请另一个运行通过数组把唯一值的新阵列中

由于数组排序,你可以检查,如果数组[n] ==阵列[N + 1]。如果没有,那么它不重复。检查N + 1的时候要小心你的数组边界。

编辑:因为这涉及到两个运行得来就为O运行(2N) - > 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:

  • Do a first run through of the array to see how many duplicates there are
  • Create a new array of size (oldSize - duplicates)
  • Do another run through of the array to put the unique values in the new array

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.

edit: because this involves two run throughs it will run in O(2n) -> O(n) time.

这篇关于在排序的Java数组复制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆