严氏北美IT公司面试真题汇总和解答论坛
Would you like to react to this message? Create an account in a few clicks or log in to continue.

Paint HouseII lc原题需bug free 可能还会问你时间复杂度 最好用标准答案

Go down

Paint HouseII lc原题需bug free 可能还会问你时间复杂度 最好用标准答案 Empty Paint HouseII lc原题需bug free 可能还会问你时间复杂度 最好用标准答案

Post by Admin Sat Oct 21, 2017 4:42 pm

//time O(n*k) optimized way  ,space O(1)
   public int minCostII(int[][] matrix) {
       if (matrix == null || matrix.length==0||matrix[0].length == 0)
        return 0;
       int preMin = 0, preSecondMin = 0, preColor = -1;
       
       for (int i = 0; i < matrix.length; i++) {
           int curMin = Integer.MAX_VALUE;
           int curSecndMin = Integer.MAX_VALUE;
           int curColor = -1;
           for (int j = 0; j < matrix[0].length; j++) {
            if(preColor == j)
            matrix[i][j] =matrix[i][j]+preSecondMin;
            else
            matrix[i][j] =matrix[i][j]+preMin;
                     
               if (matrix[i][j] < curMin) {
                   curSecndMin = curMin;
                   curMin = matrix[i][j];
                   curColor = j;
               } else if (matrix[i][j] < curSecndMin) {
                   curSecndMin = matrix[i][j];
               }              
           }
           preMin = curMin;
           preSecondMin = curSecndMin;
           preColor = curColor;
       }
       return preMin;
   }

Admin
Admin

Posts : 124
Join date : 2017-10-21

https://csinterviewquestions.forumotion.com

Back to top Go down

Back to top

- Similar topics

 
Permissions in this forum:
You cannot reply to topics in this forum