zoukankan      html  css  js  c++  java
  • 关于集合运算

    昨天被问到一个问题,就是给定两个集合Set1和Set2,求出在Set1中但是不在Set2中和在Set2中但是不在Set1中的元素集合,看了一眼,题意如下:



    题目需要求得就是除去重叠部分的元素,代码如下:

     1 import java.util.HashSet;
     2 import java.util.Set;
     3 
     4 public class Main {
     5 
     6     public static void main(String[] args) {
     7         
     8         
     9         Set<Integer> s1=new HashSet<Integer>();
    10         Set<Integer> s2=new HashSet<Integer>();
    11         
    12         for(int i=0;i<=5;i++){
    13             s1.add(i); // 0, 1, 2, 3, 4, 5
    14         }
    15         
    16         for(int i=4;i<=7;i++){
    17             s2.add(i); //4, 5, 6, 7
    18         }
    19         
    20         Set<Integer> s3=solve(s1,s2);
    21         
    22         for(Integer e:s3){
    23             System.out.println(e); //0, 1, 2, 3, 6, 7
    24         }
    25         
    26         
    27     }
    28 
    29     //做集合运算,返回      (s1 ∪ s2) - ( s1 ∩ s2 )
    30     public static <T> Set<T> solve(Set<T> s1,Set<T> s2){
    31         Set<T> res=new HashSet<T>();
    32         
    33         for(T t:s1) if(!s2.contains(t)) res.add(t);
    34         for(T t:s2) if(!s1.contains(t)) res.add(t);
    35         
    36         return res;
    37     }
    38     
    39 }



  • 相关阅读:
    windows平台下一款强大的免费代理获取工具
    彻底搞懂Git Rebase
    line-height
    text-indent
    text-decoration
    text-align
    color
    CSS属性汇总
    font
    font-style
  • 原文地址:https://www.cnblogs.com/cc11001100/p/5788875.html
Copyright © 2011-2022 走看看