leetcode 1337

Constraints:

1
2
3
4
5
1. m == mat.length
2. n == mat[i].length
3. 2 <= n, m <= 100
4. 1 <= k <= m
5. matrix[i][j] is either 0 or 1.

我写的,这个时候并没有用PriorityQueue. arr是加上位置权重之后的一维数组,a是K个数排序之后的数组,num是K个数对应的index数组,两个tmp是在用交换的方式排序.

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
class Solution {
public int[] kWeakestRows(int[][] mat, int k) {
int m = mat.length, n = mat[0].length;
double[] arr = new double[m];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
arr[i] += mat[i][j];
}
arr[i] += 0.01*i;
}

// a: after sorting; num: index
double[] a = new double[k];
int[] nums = new int[m];
for (int i = 0; i < m; ++i) {
nums[i] = i;
}
for (int i = 0; i < k; ++i) {
int index = i;
for (int j = i; j < m; ++j) {
if (arr[index] > arr[j]) {
index = j;
}
}
a[i] = arr[index];

double tmp1 = arr[i];
arr[i] = arr[index];
arr[index] = tmp1;

int tmp2 = nums[i];
nums[i] = nums[index];
nums[index] = tmp2;
}

int[] num_k = new int[k];
System.arraycopy(nums, 0, num_k, 0, k);
return num_k;
}
}

System.arraycopy是为了返回新创建的数组,用法详情见另一篇。