[leetcode] the K Weakest Rows in a Matrix

임택·2021년 2월 16일
0

알고리즘

목록 보기
31/63
post-thumbnail

problem

code

  • javascript
/**
 * @param {number[][]} mat
 * @param {number} k
 * @return {number[]}
 */
var kWeakestRows = function(mat, k) {
    const m = mat.length;
    
    const indexWithCnt = mat.map((arr, i) => {
       let count = 0;
        for (const n of arr) 
            if(n) 
                count++;
        return [i, count];
    });
    
    return indexWithCnt
      .sort((a, b) => a[1] - b[1])
      .slice(0, k)
      .map(el => el[0]);
};

Time: O(mn + nlogn)
Space: O(m + k)

  • java: interesting way to solve, using constraints
class Solution {
    public int[] kWeakestRows(int[][] mat, int k) {
        int[] sumArr = new int[mat.length];
        for(int i=0; i<mat.length; i++){
            int sum=0;
            for(int j=0; j<mat[0].length; j++){
                if(mat[i][j]==1){
                    sum++;
                }
            }
            sumArr[i]=sum*1000+i;
        }
        Arrays.sort(sumArr);
        int[] res = new int[k];
        for(int i=0; i<k; i++){
            res[i]= sumArr[i]%1000;
        }
        return res;
    }
}

Time: O(MN + NlogN)
Space: O(N)

profile
캬-!

0개의 댓글