Reputation: 2157
Working on Leetcode problem 57 Insert Interval.
I'm trying to combine two Arrays/Lists.
I want to be able to just add them in the return like in python
return res + subArry
but get complains saying I can't do that in Java.
So I then try to add subArray
to res
and run into this error.
class Solution {
public int[][] insert(int[][] intervals, int[] newInterval) {
List<int[]> res = new ArrayList<>();
for (int i = 0; i < intervals.length; i++) {
if (newInterval[1] < intervals[i][1]) {
res.add(newInterval);
List subArray = Arrays.asList(intervals).subList(i, intervals.length);
res.add(subArray);
return res;
} else if (newInterval[0] > intervals[i][1]) {
res.add(intervals[i]);
} else {
newInterval[0] = Math.min(intervals[i][0], newInterval[0]);
newInterval[1] = Math.max(intervals[i][1], newInterval[1]);
}
}
res.add(newInterval);
return res.toArray(new int[res.size()][]);
}
}
Please help. Thanks in advance!
Upvotes: 0
Views: 756
Reputation: 511
There's a couple of problems with your original code
List subArray = Arrays.asList(intervals).subList(i, intervals.length);
res.add(subArray);
//res is list<int[]>
return res;
After fixing the above issues the code below compile and runs just fine. *note I didn't check the internal logic
public static int[][] insert(int[][] intervals, int[] newInterval) {
List<int[]> res = new ArrayList<>();
for (int i = 0; i < intervals.length; i++) {
if (newInterval[1] < intervals[i][1]) {
res.add(newInterval);
List subArray = Arrays.asList(intervals).subList(i, intervals.length);
res.addAll(subArray);
return res.toArray(new int[0][]);
} else if (newInterval[0] > intervals[i][1]) {
res.add(intervals[i]);
} else {
newInterval[0] = Math.min(intervals[i][0], newInterval[0]);
newInterval[1] = Math.max(intervals[i][1], newInterval[1]);
}
}
res.add(newInterval);
return res.toArray(new int[0][]);
}
public static void main(String args[]) {
int[][] intervals = {{ 1, 2, 3, 4 }, { 8, 5, 5, 7}, { 4, 23, 34}};
int[] newInterval = {4,3,5,2};
int[][] tempt = insert(intervals,newInterval);
for (int[] row : tempt)
System.out.println(Arrays.toString(row));
}
Upvotes: 1