发布于2024-11-21 阅读(0)
扫一扫,手机访问
五种经典的Java数组去重算法详解
在Java编程中,经常会遇到需要对数组进行去重操作的情况,即去除数组中的重复元素,保留唯一的元素。下面将介绍五种经典的Java数组去重算法,并提供相应的代码示例。
import java.util.Arrays; import java.util.HashSet; public class ArrayDeduplicateExample { public static void main(String[] args) { int[] array = {1, 2, 3, 2, 4, 3, 5}; HashSet<Integer> set = new HashSet<>(); for (int i : array) { set.add(i); } int[] result = new int[set.size()]; int index = 0; for (int i : set) { result[index++] = i; } System.out.println(Arrays.toString(result)); } }
import java.util.Arrays; import java.util.TreeSet; public class ArrayDeduplicateExample { public static void main(String[] args) { int[] array = {1, 2, 3, 2, 4, 3, 5}; TreeSet<Integer> set = new TreeSet<>(); for (int i : array) { set.add(i); } Integer[] result = set.toArray(new Integer[0]); int[] deduplicatedArray = Arrays.stream(result).mapToInt(Integer::intValue).toArray(); System.out.println(Arrays.toString(deduplicatedArray)); } }
import java.util.Arrays; public class ArrayDeduplicateExample { public static void main(String[] args) { int[] array = {1, 2, 3, 2, 4, 3, 5}; int[] deduplicatedArray = Arrays.stream(array).distinct().toArray(); System.out.println(Arrays.toString(deduplicatedArray)); } }
import java.util.Arrays; public class ArrayDeduplicateExample { public static void main(String[] args) { int[] array = {1, 2, 3, 2, 4, 3, 5}; for (int i = 0; i < array.length - 1; i++) { if (array[i] != Integer.MIN_VALUE) { for (int j = i + 1; j < array.length; j++) { if (array[i] == array[j]) { array[j] = Integer.MIN_VALUE; } } } } int count = 0; for (int i = 0; i < array.length; i++) { if (array[i] != Integer.MIN_VALUE) { array[count++] = array[i]; } } int[] deduplicatedArray = Arrays.copyOf(array, count); System.out.println(Arrays.toString(deduplicatedArray)); } }
import java.util.Arrays; import java.util.HashMap; import java.util.Map; public class ArrayDeduplicateExample { public static void main(String[] args) { int[] array = {1, 2, 3, 2, 4, 3, 5}; Map<Integer, Object> map = new HashMap<>(); for (int i : array) { map.put(i, null); } int[] deduplicatedArray = new int[map.size()]; int index = 0; for (int i : map.keySet()) { deduplicatedArray[index++] = i; } System.out.println(Arrays.toString(deduplicatedArray)); } }
以上是五种经典的Java数组去重算法的详细介绍和代码示例。实际应用中,根据具体情况选择适合的去重算法,可以提高程序的性能和可读性。
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店