无码人妻精一区二区三区,eeuss影院www在线观看,无码精品久久久久久人妻中字,日韩av高清在线看片

推薦新聞
JAVA數(shù)組去重的方法
發(fā)布者:深藍(lán)互聯(lián)
發(fā)布時間:2024-09-12
點擊:次
在 Java 中可以使用多種方法對數(shù)組進(jìn)行去重。以下是幾種常見的實現(xiàn)方式:
一、使用 Set 集合
Set 集合不允許存儲重復(fù)元素,可以利用這個特性來實現(xiàn)數(shù)組去重。
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));
    }
}

二、使用雙重循環(huán)
通過遍歷數(shù)組,比較每個元素與其他元素是否重復(fù)來實現(xiàn)去重。
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));
    }
}

三、使用排序和相鄰比較
先對數(shù)組進(jìn)行排序,然后遍歷數(shù)組,比較相鄰元素是否重復(fù)。
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));
    }
}

 

關(guān)注深藍(lán)互聯(lián)公眾號
Copyright ? 2013-2025 深藍(lán)互聯(lián) 版權(quán)所有
友情鏈接: