【问题标题】:Interval List Intersections [closed]区间列表交叉点[关闭]
【发布时间】:2020-05-24 06:28:16
【问题描述】:

给定两个封闭区间列表,每个区间列表都是成对不相交且按排序顺序排列的。

返回这两个区间列表的交集。

(形式上,闭区间 [a, b] (with a

click this for example

【问题讨论】:

  • 这是在 leetcode 5 月 22 日至 28 日挑战中提出的问题

标签: java arrays arraylist data-structures


【解决方案1】:
public int[][] intervalIntersection(int[][] A, int[][] B) {

    ArrayList<ArrayList<Integer>> res =  
              new ArrayList<ArrayList<Integer>>(); 

    for(int i=0;i<A.length;i++){
        for(int j=0;j<B.length;j++){
        ArrayList<Integer> intersection = new ArrayList<Integer>();

        if(B[j][0] >= A[i][0] && B[j][0] <= A[i][1]){
            intersection.add(B[j][0]);
            intersection.add(A[i][1] <= B[j][1] ? A[i][1] : B[j][1]);
        }
        else if(A[i][0] >= B[j][0] && A[i][0] <= B[j][1]){
                intersection.add(A[i][0]);
                intersection.add(A[i][1] <= B[j][1] ? A[i][1] : B[j][1]);
            }
            if(!intersection.isEmpty())
            res.add(intersection);
        }

    }

    return res.stream().map(u -> u.stream().mapToInt(i->i).toArray()).toArray(int[][]::new);


}

}

【讨论】:

  • 请导入流
猜你喜欢
  • 1970-01-01
  • 2017-04-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-17
  • 2021-08-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多