题解 | #明明的随机数#

明明的随机数

https://www.nowcoder.com/practice/3245215fffb84b7b81285493eae92ff0

分享一个速度比较快的做法:
1.去重:用set
2.动态数组:用List
3.排序:用Arrays.sort

/**
     * 用set去重,用List动态添加数组,用Arrays.sort排序
     * @param args
     */
    public static void main(String[] args){
        Scanner scan = new Scanner(System.in);
        int times = scan.nextInt();
        List<Integer> list = new ArrayList<>();
        Set<Integer> set = new HashSet<Integer>();
        while(times > 0){
            //对整数的输入用scan.nextInt(),而不是nextLine(),这只适用于字符串
            int num = scan.nextInt();
            if(set.add(num)){
                list.add(num);
            }
            times--;
        }
        int len = list.size();
        int[] arr = new int[len];
        for(int i=0;i<len;i++){
            arr[i] = list.get(i);
        }
        Arrays.sort(arr);
        for(int i=0;i<len;i++){
            System.out.println(arr[i]);
        }

    }


全部评论

相关推荐

06-07 19:59
门头沟学院 C++
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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