算法 n1段区间 与 n2段区间求交集

如下所示:

                                        1      3        4                    9             11            13

n1段区间之间互无交集,|——|        |——————|               |————|                                         

n2段区间之间互无交集       |————|     |——|   |————|              |——————|

                                            2            5     6     7   8            10           12                  14

仅通过图示来看很容易得到交集的答案,交集是[2,3], [4,5],  [6,7],  [8,9],  [12,13],但是当区间很多时如何去求?


首先定义两个List<Long> list1=new ArrayList<Long>();   List<Long> list2=new ArrayList<Long>();

list1放置n1段区间的起始终止点 :list1.add(1);list1.add(3);...

list2放置n2段区间的起始终止点:list2.add(2);list2.add(5);.....

然后调用函数:

public List<Long> GetIntersection(List<Long> list1, List<Long> list2){
		List<Long> intersection=new ArrayList<Long>();
		
		for(int i=0;i<list1.size();i+=2){
			Long start1=list1.get(i);  Long end1=list1.get(i+1);
			for(int j=0;j<list2.size();j+=2){
				Long start2=list2.get(j);  Long end2=list2.get(j+1);
				//  |______|                                   |______|
				//             |______|     or        |______|
				if(end1<=start2 || end2<=start1){continue;}
				if(start2>start1){				    
					if(end1<end2){
					    //  |______|
						//       |______|
						intersection.add(start2);  intersection.add(end1);						
					}else{
						//  |______|
						//    |____|
						intersection.add(start2);  intersection.add(end2);	
					}
				}else{
					if(end1<end2){
					    //      |___|
						//     |______|
						intersection.add(start1);  intersection.add(end1);						
					}else{
						//       |______|
						//    |____|
						intersection.add(start1);  intersection.add(end2);	
					}
				}
			}
		}
		return intersection;
	}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值