PrimeTimeTran
PrimeTimeTran

Reputation: 2157

Java How to fix "error: incompatible types: List cannot be converted to int[]"

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

Answers (1)

Icarus
Icarus

Reputation: 511

There's a couple of problems with your original code

  1. here the subArray is of type List<int[]> and so is res. to merge two list you should use addAll()
List subArray = Arrays.asList(intervals).subList(i, intervals.length);
res.add(subArray);
  1. here you are returning res which is a list<> when the function has a return type of int[][]
            //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

Related Questions