算法题:https://leetcode-cn.com/problems/merge-intervals/
在用Java实现时,遇到了好多的问题。
第一版的Java代码如下:
import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.List; /* * @lc app=leetcode.cn id=56 lang=java * * [56] 合并区间 */ // @lc code=start class Solution { public int[][] merge(int[][] intervals) { return doMerge(intervals); } public int[][] doMerge(int[][] intervals) { Arrays.sort(intervals, new Comparator<int[]>(){ @Override public int compare(int[] m, int[] n){ return m[0] - n[0]; } }); List<List<Integer>> resList = new ArrayList<>(); List<Integer> hasMergeIndex = new ArrayList<>(); boolean isNeedAddNow = false; for (int i = 0; i < intervals.length; i++) { if(hasMergeIndex.contains(i)){ continue; } int[] now = intervals[i]; if(i == 0){ List<Integer> nowList = new ArrayList<>(); nowList.add(now[0]); nowList.add(now[1]); resList.add(nowList); } for(List<Integer> itemList : resList) { // 更新右边界 if(now[0] <= itemList.get(1) && now[0] >= itemList.get(0)) { itemList.set(1, Math.max(now[1], itemList.get(1))) ; hasMergeIndex.add(i); } // 更新左边界 else if(now[1] <= itemList.get(1) && now[1] >= itemList.get(0)) { itemList.set(0, Math.min(now[0], itemList.get(0))) ; hasMergeIndex.add(i); } else{ isNeedAddNow = true; } } if(isNeedAddNow){ List<Integer> nowList = new ArrayList<>(); nowList.add(now[0]); nowList.add(now[1]); resList.add(nowList); hasMergeIndex.add(i); } } int[][] resMerge = new int[resList.size()][2]; int j = 0; for(List<Integer> itemInt : resList){ resMerge[j][0] = itemInt.get(0); resMerge[j][1] = itemInt.get(1); j++; } return resMerge; } } // @lc code=end
主要的问题和解决方案:
1) list的修改值怎么处理, list.set(1, newValue);
2) 初始化一个 二维数组 int[][] resMerge = new int[][];
答: resMerge = resList.toArray(new int[resList.size()][2]);
3)遇到了异常:
Line 28: java.util.ConcurrentModificationException
答: 不要在迭代list的时候,同时进行修改操作,否则用其他的方法
4)
Line 56: java.lang.ArrayStoreException: arraycopy: element type mismatch: can not cast one of the elements of java.lang.Object[] to the type of the destination array, [I
[[2,3],[2,2],[3,3],[1,3],[5,7],[2,2],[4,6]]
5) 数组也可能发生 NPE, 当初始化二维数组时,不指定第2维度的大小时,就可能发生
int[][] resMerge = new int[resList.size()][2];