import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class ArrayDeduplication {
    public static int[] deduplicateUsingSet(int[] array) {
        Set<Integer> set = new HashSet<>();
        for (int num : array) {
            set.add(num);
        }
        int[] result = new int[set.size()];
        int index = 0;
        for (Integer num : set) {
            result[index++] = num;
        }
        return result;
    }
    public static void main(String[] args) {
        int[] array = {1, 2, 2, 3, 4, 4, 5};
        int[] deduplicatedArray = deduplicateUsingSet(array);
        System.out.println(Arrays.toString(deduplicatedArray));
    }
}
public class ArrayDeduplication {
    public static int[] deduplicateUsingLoop(int[] array) {
        int length = array.length;
        for (int i = 0; i < length; i++) {
            for (int j = i + 1; j < length; ) {
                if (array[i] == array[j]) {
                    int[] newArray = new int[length - 1];
                    System.arraycopy(array, 0, newArray, 0, j);
                    System.arraycopy(array, j + 1, newArray, j, length - j - 1);
                    length--;
                    array = newArray;
                } else {
                    j++;
                }
            }
        }
        int[] result = new int[length];
        System.arraycopy(array, 0, result, 0, length);
        return result;
    }
    public static void main(String[] args) {
        int[] array = {1, 2, 2, 3, 4, 4, 5};
        int[] deduplicatedArray = deduplicateUsingLoop(array);
        System.out.println(Arrays.toString(deduplicatedArray));
    }
}
import java.util.Arrays;
public class ArrayDeduplication {
    public static int[] deduplicateUsingSort(int[] array) {
        Arrays.sort(array);
        int length = array.length;
        int newLength = 1;
        for (int i = 1; i < length; i++) {
            if (array[i]!= array[i - 1]) {
                array[newLength++] = array[i];
            }
        }
        int[] result = new int[newLength];
        System.arraycopy(array, 0, result, 0, newLength);
        return result;
    }
    public static void main(String[] args) {
        int[] array = {1, 2, 2, 3, 4, 4, 5};
        int[] deduplicatedArray = deduplicateUsingSort(array);
        System.out.println(Arrays.toString(deduplicatedArray));
    }
}               
上一篇:JSON解析
下一篇:面試的Redis面試題整理