LeetCode六月挑战赛6. 6Queue Reconstruction by Height(LeetCode 406)

LeetCode六月挑战赛6. 6

Queue Reconstruction by Height(LeetCode 406)

Suppose you have a random list of people standing in a queue. Each person is described by a pair of integers (h, k), where h is the height of the person and k is the number of people in front of this person who have a height greater than or equal to h. Write an algorithm to reconstruct the queue.

Note:
The number of people is less than 1,100.

Example

Input:
[[7,0], [4,4], [7,1], [5,0], [6,1], [5,2]]

Output:
[[5,0], [7,0], [5,2], [6,1], [4,4], [7,1]]

分析

分析例子,h为当前人的身高,k为在他的前面有多少个比他身高高的人。[5,0],身高为5,在他前面没有人比他身高高或者相等,k=0,符合要求。[7,0] 在他前面没有人比他的身高高或者相等,k=0,符合要求。[5,2],身高为5,在他前面比他身高高或者相等有2个,k=2,符合要求。[6,1],身高为6,在他前面比他身高高或者相等有1个,k=1,符合要求。[4,4],身高为4,在他前面比他身高高或者相等有4个,k=4,符合要求。[7,1],身高为7,在他前面比他身高高或者相等有1个,k=1,符合要求。

思路

首先先将所有人按照身高从大到小排列, 如果身高相同,从小到大排序k。接着将排序好的数组加入到list中,位置为k,值为[h,k],因为身高已经从大到小排序,大的永远比小的先加入到result数组中,因此,k为0时,位置为0,k为1时位置为1.

思路

代码

class Solution {
    public int[][] reconstructQueue(int[][] people) {
		//第一种排序方法
		// Arrays.sort(people, new Comparator<int[]>(){
		// public int compare(int[] a1, int[] a2){
		// if(a1[0]!=a2[0]){
		// return a2[0]-a1[0];
		// }else{
		// return a1[1]-a2[1];
		// }
		// }
		// });
        //第二种排序方法
        Arrays.sort(people, (a,b) -> a[0] == b[0] ? a[1]-b[1] : b[0]-a[0]);
        
        List<int[]> result = new ArrayList<>();
        for(int i=0;i<people.length;i++){
            int[] arr = people[i];
            result.add(arr[1],arr);
        }
        
        int[][] res = new int[people.length][2];
        for(int i=0;i<people.length;i++){
            res[i]=result.get(i);
        }
        return res;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值