目前我无法从给定数组中删除重复项。我编写了一个程序,但它只返回所有零。我不能使用hashset。
public class Assignment05a
{
public static void main(String args[])
{
int[] sourceArray = {1,4,5,4,1,2,3,5,9,7,12,-5,1,4,-1,-5,12,1};
java.util.Arrays.sort(sourceArray);
eliminateDuplicates(sourceArray);
}
public static int[] eliminateDuplicates(int[] list)
{
int[] noDup = new int[list.length];
for (int c = 0; c < list.length-1; c++)
{
if (list[c] != list[c+1])
{
list[c] = noDup[c];
}
}
for(int i = 0; i < noDup.length; i++)
{
System.out.println(noDup[i]);
}
return noDup;
}
}
答案 0 :(得分:1)
我想我们可以更新eliminateDuplicates
方法,如下所示:
public static int[] eliminateDuplicates(int[] list){
List<Integer> noDup = new ArrayList<Integer>();
noDup.add(list[0]);
for (int c = 1; c < list.length-1; c++){
if(!noDup.contains(list[c])){
noDup.add(list[c]);
}
}
int[] noDupArray = new int[noDup.size()];
for(int i = 0; i < noDup.size(); i++){
noDupArray[i] = noDup.get(i);
System.out.println(noDup.get(i));
}
return noDupArray;
}
如果您不想使用List/ArrayList
,我相信您可以更新eliminateDuplicates
方法,如下所示:
public static int[] eliminateDuplicates(int[] list){
int[] noDup = new int[list.length];
noDup[0] = list[0];
int noDupCount = 1;
for (int c = 1; c < list.length-1; c++){
boolean bAlreadyAdded = false;
for (int d = 0; d < noDup.length-1; d++){
if (noDup[d] == list[c]){
bAlreadyAdded = true;
}
}
if(!bAlreadyAdded){
noDup[noDupCount++] = list[c];
}
}
int[] newUniques = new int[noDupCount];
for(int i = 0; i < noDupCount; i++){
newUniques[i] = noDup[i];
System.out.println(noDup[i]);
}
return newUniques;
}
答案 1 :(得分:0)
您可以将每个字符映射到布尔数组,并根据布尔数组索引中该字符的ascii值将其设置为true或false。看看这个: