[英]Duplicates in a sorted java array
我必须编写一个方法,该方法采用已经按数字顺序排序的int数组,然后删除所有重复的数字并返回仅包含没有重复的数字的数组。 然后必须打印出该数组,这样我就不能有任何空指针异常。 该方法必须在O(n)时间内,不能使用向量或哈希。 到目前为止,这是我所拥有的,但是它只按顺序排列前几个数字,没有重复项,然后将重复项放在数组的后面。 我无法创建一个临时数组,因为它给了我空指针异常。
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;
}
由于这似乎是一项家庭作业,因此我不想为您提供确切的代码,但是您可以执行以下操作:
由于数组已排序,因此您只需检查array [n] == array [n + 1]。 如果不是,则它不是重复项。 检查n + 1时要小心数组边界。
编辑:因为这涉及两个贯穿,它将在O(2n)-> O(n)的时间内运行。
经过测试并可以正常工作 (假设阵列已经订购)
public static int[] noDups(int[] myArray) {
int dups = 0; // represents number of duplicate numbers
for (int i = 1; i < myArray.length; i++)
{
// if number in array after current number in array is the same
if (myArray[i] == myArray[i - 1])
dups++; // add one to number of duplicates
}
// create return array (with no duplicates)
// and subtract the number of duplicates from the original size (no NPEs)
int[] returnArray = new int[myArray.length - dups];
returnArray[0] = myArray[0]; // set the first positions equal to each other
// because it's not iterated over in the loop
int count = 1; // element count for the return array
for (int i = 1; i < myArray.length; i++)
{
// if current number in original array is not the same as the one before
if (myArray[i] != myArray[i-1])
{
returnArray[count] = myArray[i]; // add the number to the return array
count++; // continue to next element in the return array
}
}
return returnArray; // return the ordered, unique array
}
不创建新数组肯定会导致整个初始数组为null。 因此,创建一个新数组来存储初始数组中的唯一值。
您如何检查唯一值? 这是伪代码
uniq = null
loop(1..arraysize)
if (array[current] == uniq) skip
else store array[current] in next free index of new array; uniq = array[current]
end loop
就像其他人提到的那样,通过数组的初始扫描来获取数组大小
uniq = null
count = 0
loop(1..arraysize)
if (array[current] == uniq) skip
else uniq = array[current] and count++
end loop
create new array of size count
public static int[] findDups(int[] myArray) {
int numOfDups = 0;
for (int i = 0; i < myArray.length-1; i++) {
if (myArray[i] == myArray[i+1]) {
numOfDups++;
}
}
int[] noDupArray = new int[myArray.length-numOfDups];
int last = 0;
int x = 0;
for (int i = 0; i < myArray.length; i++) {
if(last!=myArray[i]) {
last = myArray[i];
noDupArray[x++] = last;
}
}
return noDupArray;
}
public int[] noDups(int[] arr){
int j = 0;
// copy the items without the dups to res
int[] res = new int[arr.length];
for(int i=0; i<arr.length-2; i++){
if(arr[i] != arr[i+1]){
res[j] = arr[i];
j++;
}
}
// copy the last element
res[j]=arr[arr.length-1];
j++;
// now move the result into a compact array (exact size)
int[] ans = new int[j];
for(int i=0; i<j; i++){
ans[i] = res[i];
}
return ans;
}
第一个循环为O(n)
,第二个循环为O(n)
根据请求总计O(n)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.