【发布时间】:2013-06-11 18:24:30
【问题描述】:
我有一个相当大的 int[],它使用 Arrays.sort() 排序。我需要从数组中删除重复的元素。
这个问题源自 sedgewick 的算法书 1.1.28
1.1.28 删除重复项。修改 BinarySearch 中的测试客户端,以在排序后删除白名单中的所有重复键。
我尝试创建一个 noDupes() 方法,该方法接受一个 int[] 并返回一个删除重复项的 int[]
rank() 方法来自 sedgewick 的代码。它执行二进制搜索
public static int[] noDupes(int[] a){
Arrays.sort(a);
int maxval= a[a.length-1];
int[] nodupes = new int[maxval];
int i=0;
for(int j=0;j<a.length;j++){
int rnk = rank(a[j],nodupes);
System.out.println(a[j]+" rank="+rnk);
if (rnk < 0){
System.out.println(a[j]+" is not dupe");
nodupes[i] = a[j];
i++;
}
}
return nodupes;
}
public static int rank(int key,int[] a){
return rank(key,a,0,a.length-1);
}
public static int rank(int key,int[] a,int lo,int hi){
if(lo > hi) return -1;
int mid = lo+(hi-lo)/2;
if(key < a[mid])return rank(key,a,0,mid-1);
else if(key > a[mid])return rank(key,a,mid+1,hi);
else return mid;
}
当我用一个示例数组运行它时
int[] a =new int[]{2,2,2,3,4,4,5,6};
int[] ret = noDupes(a);
我得到了一些意想不到的输出..即使将 2 添加到 nodupes 数组中,现有元素的排名也是 -1..
2 rank=-1
2 is not dupe
2 rank=-1
2 is not dupe
2 rank=-1
2 is not dupe
3 rank=-1
3 is not dupe
4 rank=-1
4 is not dupe
4 rank=4
5 rank=-1
5 is not dupe
6 rank=-1
6 is not dupe
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 6
at ...noDupes(BinSearch.java:85)
at ...main(BinSearch.java:96)
我不知道我做错了什么......有人可以帮忙吗?
【问题讨论】:
-
为什么不能使用
Set<Integer>? -
@sanbhat - 因为这不是练习的目的。
-
我正在尝试在不使用任何库类的情况下学习如何做到这一点。我认为这个练习意味着使用二进制搜索来解决这个问题
-
这里有问题。如果数组已经排序,您可以通过线性扫描找到重复项。无需二分查找。
-
@EJP 你是对的..线性扫描就可以了
标签: java arrays binary-search duplicate-removal