[LeetCode No.1030] 距离顺序排列矩阵单元格

题目

题解

题解一:
最容易的方法就是直接用二维数组存储矩阵的点,然后使用自定义的Arrays.sort()方法进行排序(int compare(T o1, T o2) 是“比较o1和o2的大小”。返回“负数”,意味着“o1比o2小”;返回“零”,意味着“o1等于o2”;返回“正数”,意味着“o1大于o2”。)

package No1030;

import java.util.*;

class Solution {
    public static int[][] allCellsDistOrder(int R, int C, int r0, int c0) {
		int [][]answer = new int[R*C][];
		
		for(int i=0;i<R;i++){
			for(int j=0;j<C;j++){
			answer[i*C+j] = new int[]{i,j};
			}
		}
		
		Arrays.sort(answer,new Comparator<int[]>(){
			@Override
			public int compare(int[] o1, int[] o2) {
				return Math.abs(o1[0]-r0)+Math.abs(o1[1]-c0)-Math.abs(o2[0]-r0)-Math.abs(o2[1]-c0);
			}
			
		});
    	
    	return answer;
    	
    }
   
    public static void main(String[] args){
    	int [][] answer = allCellsDistOrder(1, 2, 0, 0);
    	for(int i[]:answer){
    		System.out.print(i[1]);
    	}
    }
}

题解二:
实际在枚举所有点时,我们可以直接按照哈曼顿距离分桶。这样我们就可以实现线性的桶排序。
关于桶排序https://blog.csdn.net/qq_27124771/article/details/87651495

package No1030;

import java.math.*;
import java.util.*;

public class Solution2 {
    public int[][] allCellsDistOrder(int R, int C, int r0, int c0) {
		int Bucket_num = 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 <=Bucket_num; i++){
			bucket.add(new ArrayList<int []>());
		}
		
		for(int i = 0; i < R; i++){
			for(int j = 0; j < C; j++){
				int dist = Dist(i,j,r0,c0);
				bucket.get(dist).add(new int[]{i,j});
			}
		}
		
		int[][] answer = new int [R*C][];
		int index = 0;
		for(int i = 0; i<Bucket_num; i++){
			List<int[]> temp = bucket.get(i);
			for(int [] a:temp){
			answer[index++] = a;
			}
		}
		return answer;
    }
    
    public int Dist(int r,int c,int r0,int c0){
		return Math.abs(r-r0)+Math.abs(c-c0);
	}
    
    public static void main(String[] args){
    	
    }
}

posted @ 2020-11-26 00:23  饼先生  阅读(62)  评论(0编辑  收藏  举报