Java O(1) space solution but slow


  • 0
    M

    As title said my solution works in place. However, depending on the concrete instance of the Triangle internal Lists the remove and add operations can take O(n) time. In such cases the time complexity is O(n^3).

    public int minimumTotal(List<List<Integer>> triangle) {
        if(triangle == null || triangle.size() == 0)
            return 0;
            
        List<Integer> currentRow, upperRow;
        for(int i = triangle.size() - 1; i > 0; --i){
            currentRow = triangle.get(i);
            upperRow = triangle.get(i-1);
            for(int j = 0; j < upperRow.size(); ++j){
                int current = upperRow.remove(j);
                upperRow.add(j , current + Math.min(currentRow.get(j),
                                                  currentRow.get(j+1)
                                                  )
                             );
            }
        }
        return triangle.get(0).get(0);
    }

  • 3
    F

    you should try to use: upperRow.set(index,Object) ;O(1)

    upperRow.add() and remove() method's complexity is O(n);


  • 0
    M

    Thank you mate! I seriously forgot about it. However, the problem remains for linked lists.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.