要使用Stream流对数组进行去重,可以先将数组转换为Stream流,然后使用distinct()方法去重,最后将结果转换回数组。

具体的代码如下所示:

import java.util.Arrays;
import java.util.stream.Collectors;

public class Solution {
    public ListNode removeDuplicateNodes(ListNode head) {
        if (head == null) {
            return null;
        }
        
        // 将链表转换为数组
        int[] nums = new int[0];
        ListNode curr = head;
        while (curr != null) {
            nums = Arrays.copyOf(nums, nums.length + 1);
            nums[nums.length - 1] = curr.val;
            curr = curr.next;
        }
        
        // 使用Stream流对数组进行去重
        int[] distinctNums = Arrays.stream(nums).distinct().toArray();
        
        // 将去重后的数组转换为链表
        ListNode dummy = new ListNode(0);
        curr = dummy;
        for (int num : distinctNums) {
            curr.next = new ListNode(num);
            curr = curr.next;
        }
        
        return dummy.next;
    }
}

上述代码中,首先将链表转换为数组,然后使用Stream流对数组进行去重,最后再将去重后的数组转换为链表

面试题 0201 移除重复节点提示简单189相关企业编写代码移除未排序链表中的重复节点。保留最开始出现的节点。示例1 输入:1 2 3 3 2 1 输出:1 2 3示例2 输入:1 1 1 1 2 输出:1 2想要用stream流去重distinct应该怎么把数组变成一个集合

原文地址: https://www.cveoy.top/t/topic/iD8w 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录