题解 | #整型数组合并#

整型数组合并

http://www.nowcoder.com/practice/c4f11ea2c886429faf91decfaf6a310b

方法1:走捷径,用TreeSet就行。

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        while (in.hasNextInt()) { 
            Set<Integer> set = new TreeSet<>();
            int n1 = in.nextInt();
            for(int i =0;i<n1;++i)
                set.add(in.nextInt());
            int n2 = in.nextInt();
            for(int i =0;i<n2;++i){
                 set.add(in.nextInt());
            }
            for(int i:set){
                System.out.print(i);
            }
        }
    }
}

方法二:优先队列,设置一个标记记录上次打印的元素,如果相同就不打印。

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        while (in.hasNextInt()) { 
             PriorityQueue<Integer> que = new PriorityQueue(new Comparator<Integer>(){
                public int compare(Integer o1,Integer o2){
                    return o1-o2;
                }
            });
            int n1 = in.nextInt();
            for(int i =0;i<n1;++i)
                que.offer(in.nextInt());
            int n2 = in.nextInt();
            for(int i =0;i<n2;++i)
                que.offer(in.nextInt());
            int pre = que.poll();
            System.out.print(pre);
            while(!que.isEmpty()){
                int temp  = que.poll();
                if(temp!=pre){
                    pre = temp;
                     System.out.print(pre);
                }
            }
        }
    }
}
全部评论

相关推荐

09-14 17:23
门头沟学院
故事和酒66:所以说副业很重要,程序员干到40岁,再怎么也赚300万了,吃吃利息也够活下去
点赞 评论 收藏
分享
评论
4
2
分享

创作者周榜

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