-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1337. The K Weakest Rows in a Matrix.java
62 lines (46 loc) · 1.69 KB
/
1337. The K Weakest Rows in a Matrix.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
class Solution {
public int[] kWeakestRows(int[][] mat, int k) {
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
for(int i = 0; i < mat.length; i++)
{
int c = 0;
for(int j = 0; j < mat[i].length; j++)
{
if(mat[i][j] == 1)
c++;
}
map.put(i, c);
}
System.out.println(map);
Map res = sortByValue(map);
System.out.println(res);
int[] arr = new int[k];
int i = 0;
Iterator<Integer> itr = res.keySet().iterator();
while (itr.hasNext() && i < k) {
arr[i] = itr.next();
i++;
}
return arr;
}
public HashMap<Integer, Integer> sortByValue(HashMap<Integer, Integer> hm)
{
// Create a list from elements of HashMap
List<Map.Entry<Integer, Integer> > list =
new LinkedList<Map.Entry<Integer, Integer> >(hm.entrySet());
// Sort the list
Collections.sort(list, new Comparator<Map.Entry<Integer, Integer> >() {
public int compare(Map.Entry<Integer, Integer> o1,
Map.Entry<Integer, Integer> o2)
{
return (o1.getValue()).compareTo(o2.getValue());
}
});
// put data from sorted list to hashmap
HashMap<Integer, Integer> temp = new LinkedHashMap<Integer, Integer>();
for (Map.Entry<Integer, Integer> aa : list) {
temp.put(aa.getKey(), aa.getValue());
}
return temp;
}
}s