二维坐标,x从小到大排列,y从大到小排列

目前能想到的最完美的方案,还没得到扩展,仅仅可用于二维数组

重点思路:将xy捆绑到一块排序,因为y是倒叙需要计算下对应正序时的值,也就是拿y组最大值减去当前值,得到x升序y升序组合数组xy,需要考虑到y组位数问题

import java.util.Arrays;


public class Test {
	public static void main(String[] args) {
		Test test = new Test();
		int[][] param = new int[][] { { 3, 20 }, { 1, 9 }, { 5, 8 }, { 2, 1 }, { 3, 6 }, { 2, 1 } };
		int[][] result = test.sortArrayTwoDimension(param);
		for (int i = 0; i < result.length; i++) {
			System.out.println(result[i][0] + "  " + result[i][1]);
		}
	}


	public int[][] sortArrayTwoDimension(int[][] param) {
		int[] x = new int[param.length];
		int[] y = new int[param.length];
		for (int i = 0; i < param.length; i++) {
			int[] temp = param[i];
			x[i] = temp[0];
			y[i] = temp[1];
		}
		
		int maxy = 0;
		for (int i = 0; i < y.length; i++) {
			if (y[i] > maxy) {
				maxy = y[i];
			}
		}
		// 将y数组用最大值-原有值获取倒叙值数组
		int[] sortp = new int[param.length];
		for (int i = 0; i < y.length; i++) {
			sortp[i] = maxy - y[i];
		}
		
		// y数组最大长度
		int ylmax = String.valueOf(maxy).length();
		long[] xy = new long[param.length];
		for (int i = 0;i<x.length;i++) {
			xy[i] = Long.valueOf(String.valueOf(x[i]) + Test.addZeroForNum(String.valueOf(sortp[i]), ylmax));
		}
		
		Arrays.sort(xy);


		int index = 0;
		int[][] result = new int[x.length][2];
		for (int j = 0; j < xy.length; j++) {
			for (int i = 0; i < x.length; i++) {
				if (xy[j] == Long.valueOf(String.valueOf(x[i]) + Test.addZeroForNum(String.valueOf(sortp[i]), ylmax))) {
					result[index] = new int[]{x[i],y[i]};
					index++;
					break;
				}
			}
		}
		return result;
	}
	
	public static String addZeroForNum(String str, int strLength) {
		int strLen = str.length();
		if (strLen < strLength) {
			while (strLen < strLength) {
				StringBuffer sb = new StringBuffer();
				sb.append("0").append(str);
				str = sb.toString();
				strLen = str.length();
			}
		}
		return str;
	}
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值