1337. The K Weakest Rows in a Matrix

1337. The K Weakest Rows in a Matrix

class Solution {
    private class Row{
	int rowNum;
	int soliders;
	public Row(int rowNum, int soliders) {
		this.rowNum = rowNum;
		this.soliders = soliders;
 	}
	public int getRowNum() {
		return rowNum;
	}
	public void setRowNum(int rowNum) {
		this.rowNum = rowNum;
	}
	public int getSoliders() {
		return soliders;
	}
	public void setSoliders(int soliders) {
		this.soliders = soliders;
	}
	
}
   public int[] kWeakestRows(int[][] mat, int k) {
    	int rowCount =0;
    	ArrayList rows = new ArrayList();
    	int i = 0;
        for(i =0; i < mat.length; i++) {
        	rowCount =0;
        	for (int j = 0; j < mat[i].length; j++) {
        		if(mat[i][j] == 1) rowCount++;
        	}
        	rows.add(new Row(i,rowCount));
        }
             Collections.sort(rows, new Comparator(){
			@Override
			public int compare(Row o1, Row o2) {
				if (o1.getSoliders() == o2.getSoliders()) 
					{
					return  ((Integer)o1.getRowNum()).compareTo((Integer)o2.getRowNum());
					}
				return ((Integer)o1.getSoliders()).compareTo((Integer)o2.getSoliders());
			}});
        int[] out = new int[k];
        for (int j = 0; j < out.length; j++) {
        	out[j] = rows.get(j).getRowNum();
        }
        return out;
    }
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s