题解 | 数组中只出现一次的两个数字

import java.util.*;
public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * @param nums int整型一维数组
     * @return int整型一维数组
     */
    public int[] FindNumsAppearOnce(int[] nums) {
        // write code here
        HashMap<Integer, Integer> mp = new HashMap<>();
        int[] ans = {-1, -1};
        for (int k : nums) {
            int count = 0;
            if (mp.get(k) == null) {
                mp.put(k, 1);
            } else {
                count = mp.get(k) + 1;
                mp.put(k, count);
            }
        }
        for (int num : nums) {
            if (mp.get(num) == 1) {
//                其实这里使用List的push会简洁高效一点。// 使用Collections.sort()对列表进行升序排序
                for (int j = 0; j < ans.length; ++j) {
                    if (ans[j] == -1) {
                        ans[j] = num;
                        break;
                    }
                }
            }
        }

//        Arrays.sort(ans,  (x, y) -> (x - y));// int(基础数据类型)数组不能像这样自定义排序。因为java泛型不支持基础数据类型作为模版T
        Arrays.sort(ans);
/*
//      int数组转为Integer
        Integer[] interArray = Arrays.stream(ans)
                .boxed() // 将 int 转换为 Integer(装箱)
                .toArray(Integer[]::new); // 转换为 Integer 数组
//        使用lambda,简洁
        Arrays.sort(interArray, (x, y) -> x - y);

//        使用匿名函数,不太简洁:
//        Arrays.sort(interArray, new Comparator<Integer>() {
//            @Override
//            public int compare(Integer x, Integer y) {
//                return x - y;
//            }
//        });
// 使用Stream API将Integer数组转换为int数组
        int[] intArray = Arrays.stream(interArray)
                .filter(i -> i != null) // 过滤掉可能的null值
                .mapToInt(Integer::intValue)//转换为 IntStream(基本类型流)
                .toArray(); // 转换为数组
        return intArray;

 */
        return ans;
    }
}

这题,不难,对语法足够熟悉就好。

如果出现的是升序排序的话,自定义比较器还是挺恶心的(刚开始用),得作类型转换。

全部评论

相关推荐

苍蓝星上艾露:这简历。。。可以试试我写的开源简历优化工具https://github.com/weicanie/prisma-ai
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务