Leetcode-1030-距离顺序排列矩阵单元格

Leetcode-1030-距离顺序排列矩阵单元格

题目描述

  • 给出 R 行 C 列的矩阵,其中的单元格的整数坐标为(r, c),满足 0 <= r < R0 <= c < C。

    另外,我们在该矩阵中给出了一个坐标为(r0, c0) 的单元格。

    返回矩阵中的所有单元格的坐标,并按到 (r0, c0) 的距离从最小到最大的顺序排,其中,两单元格(r1, c1) 和 (r2, c2) 之间的距离是曼哈顿距离,|r1 - r2| + |c1 - c2|。(你可以按任何满足此条件的顺序返回答案。)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
示例 1:

输入:R = 1, C = 2, r0 = 0, c0 = 0
输出:[[0,0],[0,1]]
解释:从 (r0, c0) 到其他单元格的距离为:[0,1]

示例 2:

输入:R = 2, C = 2, r0 = 0, c0 = 1
输出:[[0,1],[0,0],[1,1],[1,0]]
解释:从 (r0, c0) 到其他单元格的距离为:[0,1,1,2]
[[0,1],[1,1],[0,0],[1,0]] 也会被视作正确答案。

示例 3:

输入:R = 2, C = 3, r0 = 1, c0 = 2
输出:[[1,2],[0,2],[1,1],[0,1],[1,0],[0,0]]
解释:从 (r0, c0) 到其他单元格的距离为:[0,1,1,2,2,3]
其他满足题目要求的答案也会被视为正确,例如 [[1,2],[1,1],[0,2],[1,0],[0,1],[0,0]]。

方法一 : 暴力排序

  • 最容易想到的方法是首先存储矩阵内所有的点,然后将其按照哈曼顿距离直接排序。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public int[][] allCellsDistOrder(int R, int C, int r0, int c0) {
int[][] ret = new int[R * C][];
for (int i = 0; i < R; i++) {
for (int j = 0; j < C; j++) {
ret[i * C + j] = new int[]{i, j};
}
}
Arrays.sort(ret, new Comparator<int[]>() {
public int compare(int[] a, int[] b) {
return (Math.abs(a[0] - r0) + Math.abs(a[1] - c0)) - (Math.abs(b[0] - r0) + Math.abs(b[1] - c0));
}
});
return ret;
}
}

mark

方法二 :桶排序

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
class Solution {
// 使用桶排序
public int[][] allCellsDistOrder(int R, int C, int r0, int c0) {
// 计算需要几个桶 并把创建相应数量的桶
int maxDist = Math.max(r0,R - 1 - r0) + Math.max(c0, C- 1 - c0);
List<List<int[]>> bucket = new ArrayList<List<int[]>>();
for(int i = 0; i <= maxDist;i++){
bucket.add(new ArrayList<int[]>());
}

// 计算出哈曼顿距离 并结果加入到相应的桶里面(时间复杂度 O(RC))
for(int i = 0;i < R;i++){
for(int j = 0;j < C;j++){
int d = dist(i,j,r0,c0);
bucket.get(d).add(new int[]{i,j});
}
}

// 创建结果集,并把Arraylist<List<int[]> 转换成int[][]
int[][] ret = new int[R*C][2];
int idx = 0;
// 遍历每个桶,把桶中的元素加入到结果集中
for(int i = 0;i <= maxDist;i++){
for(int[] it:bucket.get(i)){
ret[idx++] = it;
}
}
return ret;
}

// 计算哈曼顿距离(排序方法)
public int dist(int r1,int c1,int r2,int c2){
return Math.abs(r1 - r2) + Math.abs(c1 - c2);
}
}

mark

打赏
  • 版权声明: 本博客所有文章除特别声明外,均采用 Apache License 2.0 许可协议。转载请注明出处!
  • © 2019-2022 Zhuuu
  • PV: UV:

请我喝杯咖啡吧~

支付宝
微信