推荐新闻
JAVA数组去重的方法
发布者:深蓝互联
发布时间:2024-09-12
点击:
在 Java 中可以使用多种方法对数组进行去重。以下是几种常见的实现方式:
一、使用 Set 集合
Set 集合不允许存储重复元素,可以利用这个特性来实现数组去重。
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));
    }
}

 

文章来自深蓝互联http://www.szdbi.com/WEBkaifajishu/539.html转载请注明出处!

关注深蓝互联公众号
Copyright © 2013-2024 深蓝互联 版权所有
友情链接: