利用方法输入一数组,找出数组中只出现过一次的数字,我这个为什么最后会多一个重复的?求大神帮我解答,谢谢!

解决方案 »

  1.   

    貌似if()count2==9)哪里
    把数组最后一个数,再加入list了.
      

  2.   

    因为2是第十个元素,和前面9个都不相等,if(count2==9)里面的语句在j=9和j=10的时候执行了2次
      

  3.   

    当 i=9, j=8 时,count2=9,符合if(count2==9) 的条件,执行list.add(arr[i]),然后循环继续,i=9,j=9时,a[i] == a[j],count2不会自增 ,此时 count2=9,符合if(count2==9) 的条件,执行list.add(arr[i])。
    不重复用如下算法会更简单
    public static void suan(int[] arr) {
    ArrayList<Integer> list = new ArrayList<Integer>();
    for (int i = 0; i < arr.length; i++) {
    for (int j = i; j < arr.length; j++) {
    if (arr[i] == arr[j]) {
    break;
    }
    }
    list.add(arr[i]);
    }
    System.out.println();
    System.out.println("出现一次的数字有:");
    System.out.println(list);
    }
      

  4.   

    上面代码写错了,修改一下
    public static void suan(int[] arr) {
    ArrayList<Integer> list = new ArrayList<Integer>();
    for (int i = 0; i < arr.length; i++) {
    for (int j = 0; j < arr.length; j++) {
    if (arr[i] == arr[j] && i != j) {
    break;
    }
    if (j == arr.length - 1) {
    list.add(arr[i]);
    }
    }
    }
    System.out.println("出现一次的数字有:");
    System.out.println(list);
    }
      

  5.   

    直接用jdk的hash算法更方便
    import java.util.HashSet;
    import java.util.Set;public class Test38 { public static void main(String[] args) {
    int[] arr = {1, 2, 3, 4, 5, 3, 4, 4};
    suan(arr);
    }

    public static void suan(int[] arr){
    Set<Integer> s1 = new HashSet(arr.length);
    Set<Integer> s2 = new HashSet(arr.length);

    for(int i : arr)
    if(!s1.add(i))
    s2.add(i);

    System.out.println(s2);

    }

    }