用Java求整数区间[a,b]和[c,d]的交集、并集

1. 求整数区间[a,b]和[c,d]的交集、并集

package cn.oop.nk;

/**
 * 求整数区间[a,b]和[c,d]的交集、并集
 * @author 温暖wk
 *
 */
public class Demo02 {

    public static void main(String[] args) {
         getInterval(1,9,3,10);
         getsum(1,9,3,10);

    }

    //求交集
    public static void getInterval(int s1,int e1,int s2,int e2){
          if(e1 < s2 || e2 < s1) {
              System.out.println("两集合无交集");
          }else{
              System.out.println("两集合的交集为:[" + Math.max(s1,s2) + ","  +  Math.min(e1,e2) + "]");
          }
     }
    //求并集
    public static void getsum(int s1,int e1,int s2,int e2){
          if(s1 < s2 || e2 > e1) {
              System.out.println("两集合的并集为:[" + Math.min(s1,s2) + ","  +  Math.max(e1,e2) + "]");
          }
   }
}
可以使用Java中的Set集合来实现求解两个集合的并集交集和差集,具体代码如下: ```java import java.util.*; public class SetOperations { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("请输入第一个集合:"); Set<Integer> set1 = new HashSet<>(); String[] s1 = sc.nextLine().split(" "); for (String str : s1) { set1.add(Integer.parseInt(str)); } System.out.print("请输入第二个集合:"); Set<Integer> set2 = new HashSet<>(); String[] s2 = sc.nextLine().split(" "); for (String str : s2) { set2.add(Integer.parseInt(str)); } // 求并集 Set<Integer> unionSet = new HashSet<>(set1); unionSet.addAll(set2); System.out.println("并集为:" + unionSet); // 求交集 Set<Integer> intersectionSet = new HashSet<>(set1); intersectionSet.retainAll(set2); System.out.println("交集为:" + intersectionSet); // 求差集 Set<Integer> differenceSet = new HashSet<>(set1); differenceSet.removeAll(set2); System.out.println("第一个集合与第二个集合的差集为:" + differenceSet); differenceSet = new HashSet<>(set2); differenceSet.removeAll(set1); System.out.println("第二个集合与第一个集合的差集为:" + differenceSet); } } ``` 在该代码中,我们首先使用`Scanner`类从控制台读取输入的两个集合,然后通过`HashSet`类构造出两个集合对象`set1`和`set2`。接下来,我们分别使用`addAll()`、`retainAll()`和`removeAll()`方法来求出两个集合的并集交集和差集,并将结果打印输出。
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值