题目
这道题可以用map来实现,记录顺序与下标之间的关系,但是有重复的情况,还要用到list,太麻烦了。我想的是直接拼接字符串,重写排序。
class Solution {
public int[] kWeakestRows(int[][] mat, int k) {
String[] s = new String[mat.length];
for(int i=0;i<mat.length;i++){
int count = 0;
for(int j=0;j<mat[0].length;j++){
if(mat[i][j]==0) break;
count++;
}
s[i] = count+"-"+i;
}
Comparator<String> cmp = new Comparator<String>(){
public int compare(String a,String b){
String[] tmp1 = a.split("-");
String[] tmp2 = b.split("-");
if(Integer.parseInt(tmp1[0])>Integer.parseInt(tmp2[0])){
return 1;
}else if(Integer.parseInt(tmp1[0])<Integer.parseInt(tmp2[0])){
return -1;
}else{
if(Integer.parseInt(tmp1[1])>Integer.parseInt(tmp2[1])){
return 1;
}else{
return -1;
}
}
}
};
Arrays.sort(s,cmp);
int[] res = new int[k];
for(int i=0;i<k;i++){
String[] tmp3 = s[i].split("-");
res[i] = Integer.parseInt(tmp3[1]);
}
return res;
}
}