Passion and Patience

Work Hard, Play Hard

导航

Leetcode 只出现一次的数据

Day 7 第三题

我的思路:利用Stream 的distinct()方法找出不重复的,但后续思路想不出来。
class Solution {
    public int singleNumber(int[] nums) {
        int n = nums.length;
        IntStream stream = Arrays.stream(nums);//转为stream流

        Stream<Integer> boxed = stream.boxed(); //装箱为Integer

        List<Integer> collect = boxed.collect(Collectors.toList()); //收集
        
        List<Integer> IntegerList = Arrays.stream(nums).distinct().boxed().collect(Collectors.toList()); // 利用Stream 的distinct()方法来去除重复元素

        int i=0;
        while (IntegerList.contains(nums[i])){
            // 会连续删除元素,indexOf可以在arraylist中找特定的元素的idx
            IntegerList.remove(IntegerList.indexOf(nums[i++])); // wrong step 
            if(i>=n){
                i=0;
            }

        }

        return nums[i];
    }
}
力扣官方解答:利用异或类型的巧算,得出唯一出现一次的数字。
class Solution {
    public int singleNumber(int[] nums) {
        int single = 0;
        for (int num : nums) {
            single ^= num;
        }
        return single;
    }
}

posted on 2024-03-21 23:24  安静的聆  阅读(8)  评论(0)    收藏  举报