• 算法训练 集合运算


      算法训练 集合运算  
    时间限制:1.0s   内存限制:512.0MB
          
    问题描述
      给出两个整数集合A、B,求出他们的交集、并集以及B在A中的余集。
    输入格式
      第一行为一个整数n,表示集合A中的元素个数。
      第二行有n个互不相同的用空格隔开的整数,表示集合A中的元素。
      第三行为一个整数m,表示集合B中的元素个数。
      第四行有m个互不相同的用空格隔开的整数,表示集合B中的元素。
      集合中的所有元素均为int范围内的整数,n、m<=1000。
    输出格式
      第一行按从小到大的顺序输出A、B交集中的所有元素。
      第二行按从小到大的顺序输出A、B并集中的所有元素。
      第三行按从小到大的顺序输出B在A中的余集中的所有元素。
    样例输入
    5
    1 2 3 4 5
    5
    2 4 6 8 10
    样例输出
    2 4
    1 2 3 4 5 6 8 10
    1 3 5
    样例输入
    4
    1 2 3 4
    3
    5 6 7
    样例输出
    1 2 3 4 5 6 7
    1 2 3 4
    import java.util.Arrays;
    import java.util.Scanner;
    public class Main {
    
        public static void main(String[] args) {
            // TODO Auto-generated method stub
            Scanner sc=new Scanner(System.in);
            int n=sc.nextInt();
            int a[]=new int[n];
            for(int i=0;i<n;i++)
                a[i]=sc.nextInt();
            int m=sc.nextInt();
            int b[]=new int[m];
            for(int i=0;i<m;i++)
                b[i]=sc.nextInt();
            
            int union[]=new int[n+m];
            int in[]=new int[n+m];
            
            int k=0;
            for(int i=0;i<n;i++){
                for(int j=0;j<m;j++){
                    if(a[i]==b[j])in[k++]=a[i];
                }
            }
            int k2=0;
            int c[]=new int[n];
            for(int i=0;i<n;i++)c[i]=a[i];
            for(int i=0;i<n;i++){
                for(int j=0;j<m;j++){
                    if(c[i]==b[j]){
                        c[i]=1001;
                    }
                }
                
                }
            
            for(int i=0;i<m;i++){
                union[k2++]=b[i];
            }
            for(int i=0;i<n;i++){
                if(c[i]!=1001)
                    union[k2++]=c[i];
            }
            
            
            Arrays.sort(c);
            Arrays.sort(union,0,k2);
            Arrays.sort(in,0,k);
            for(int i=0;i<k;i++)
                System.out.print(in[i]+" ");
            System.out.println();
            for(int i=0;i<k2;i++)
                System.out.print(union[i]+" ");
            System.out.println();
            for(int i=0;i<n;i++)
                if(c[i]!=0 && c[i]!=1001)
                    System.out.print(c[i]+" ");
            System.out.println();
    
    
        }
    
    }
  • 相关阅读:
    Scrapy settings 并发数更改
    tp5 规避 [ error ] 未定义数组索引
    967. Numbers With Same Consecutive Differences
    846. Hand of Straights
    1103. Distribute Candies to People
    559. Maximum Depth of N-ary Tree
    1038. Binary Search Tree to Greater Sum Tree
    538. Convert BST to Greater Tree
    541. Reverse String II
    1551. Minimum Operations to Make Array Equal
  • 原文地址:https://www.cnblogs.com/watchfree/p/5769086.html
Copyright © 2020-2023  润新知