我写了一个数组长度可以是任意大小的(当然,数组长度小于2的排除掉了),得到不重复元素个数的程序,请指点!
import java.util.Arrays;
public class NonDuplicates {
public static void main(String[] argus){
System.out.println("a1:"+nondup(new int[]{}));
System.out.println("a2:"+nondup(new int[]{1}));
System.out.println("a3:"+nondup(new int[]{1,1}));
System.out.println("a4:"+nondup(new int[]{1,3,2,1,5,5}));
System.out.println("a5:"+nondup(new int[]{3,2,1,2,5,3,4,6,7,9}));
}
static int nondup(int[] a){
if(a.length<2)
return 0;
int count=0;
Arrays.sort(a);
if(a[0]==a[1])count++;
if(a[a.length-1]==a[a.length-2])
count++;
for(int i=1;i<a.length-1;i++){
if(a[i]==a[i-1]||a[i]==a[i+1]){
count++;
}
}
return a.length-count;
}
}
|