一维数组去重

/**
* Description: 一维数组去重
* Author liu kai
* Data 2016/7/25 14:02
* @param
* @return void
*/
public static void test (int[] arr){
   int len = 0;        //标记去重的次数
   int newLen = 0;
   int[] newArray;
   for (int i = 0; i < arr.length; i++) {
       for (int j = i+1; j < arr.length; j++) {
           if (arr[i] == -1) {
               continue;
           } else {
               if (arr[i] == arr[j]) {
                   arr[j] = -1;
                   len++;
               }
           }
       }
   }

   //不使用 list 的情况下,用数组重新封装结果
   newArray = new int[arr.length - len];
   for (int i = 0; i < arr.length; i++) {
       if (arr[i] != -1) {
           newArray[newLen] = arr[i];
           newLen++;
       }
   }
   printResult (newArray);
}

public static void printResult(int[] arr) {
   for (int i = 0; i < arr.length; i++) {
       System.out.println(arr[i]);
   }
}

public static void main(String[] args) {
   int[] arr = {1, 4, 6, 4, 3, 5, 5, 0, 9, 8, 2, 4, 3, 8, 9, 7};
   test(arr);
}

你可能感兴趣的:(一维数组去重)