Don't know what's wrong with my java solution


  • 0
    V

    /* The idea is that, if the path from previous list is on the node i, then the next node on the current list will be the smaller value between node i and node i + 1.

    after submission, it says: java.lang.IndexOutOfBoundsException: Index: 0, Size: 0, it is on the line: list = triangle.remove(0). Last execute input is [[-10]].

    */

    public int minimumTotal(List<List<Integer>> triangle) {
        if(triangle == null){
            return 0;
        }
        List<Integer> list = new ArrayList<Integer>();
        int result = 0;
        int lastPosition = 0;
        
        while(triangle != null){
           list = triangle.remove(0);
           if(list.size() == 1){
        	   result = list.get(0).intValue();
           }
           if(lastPosition + 1 < list.size()){
           
             if(list.get(lastPosition).intValue() < list.get(lastPosition+1).intValue()){
                 result = result + list.get(lastPosition).intValue();
               
             }else{
                 result = result + list.get(lastPosition+1).intValue();
                 lastPosition++;
             }
        }
    }
           
        
       return result; 
        
    }

  • 0
    Q

    You are never exiting the while loop. On second pass you will get IndexOutOfBounds error.


Log in to reply
 

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