• [leetcode] 406.Queue Reconstruction by Height


    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]]

    题目给出一系列数组,每个数组代表一个人,其中每个数组的第一个数代表这个人的身高,第二个数代表这个人前面有多少个身高高于或等于他的人;要求通过算法将这些人安放在正确的位置上,代码如下:

    point:为什么要先按身高降序排,身高相等的时候再按前面的人数升序排?

       1、因为按身高进行降序排列以后,从前向后遍历排序以后的数组(人)时,当发现位置不对的数组(人)时,只可能是这个人前面的不比他矮的人数多于他前面应有不比他矮的人数,此时只需要把他往前移动到正确的位置即可,当将其向前移动时,由于前面的人都不比他矮,所以并不会改变之前站好位置的人的正确性。

       2、由于已经按身高进行了降序排列,所以遍历到某个数组(人)时,很容易可以得到其前面有几个不比他矮的人数,即遍历index:i。

    public class Solution {
    	public int[][] reconstructQueue(int[][] people) {
    		// 先按身高降序对数组进行排序,如果身高一样,则根据前面的人数按升序排
    		Arrays.sort(people, new Comparator<int[]>() {
    			// 其实new接口就相当于new一个实现这个接口的匿名内部类,要new 这个匿名内部类就必须实现接口的抽象方法
    			// 实现抽象方法
    			// compare方法,返回-1:01在前,返回1,o2在前
    			public int compare(int[] o1, int[] o2) {
    				if (o1[0] > o2[0]) {
    					return -1;
    				} else if (o1[0] < o2[0]) {
    					return 1;
    				} else {
    					if (o1[1] < o2[1]) {
    						return -1;
    					} else {
    						return 1;
    					}
    				}
    			}
    		});
    		// 拍好序后遍历,判断是否位置正确,如不正确则往前移至正确位置(只有往前移才能到正确位置)
    		for (int i = 0; i < people.length; i++) {
    			// 判断位置是否正确
    			if (people[i][1] != i) {
    				dealArray(people, people[i][1], i);
    			}
    		}
    		return people;
    	}
    
    	/**
    	 * 将j位上的数插入到i位上,然后数组依次后移 ej:1-2-3-4-5-6 i=1,j=4,----> 1-5-2-3-4-6
    	 * @param arrays
    	 * @param i
    	 * @param j
    	 */
    	private void dealArray(int[][] arrays, int i, int j) {
    		int[] temp = arrays[j];
    		while (j > i) {
    			arrays[j] = arrays[j - 1];
    			j--;
    		}
    		arrays[i] = temp;
    	}
    }
    

      

  • 相关阅读:
    CSS 3中细线边框如何实现?
    【SPL标准库专题(1)】 SPL简介
    【PSR规范专题(5)】PSR-4 改进后的自动加载规范
    【PSR规范专题(4)】PSR-3 日志接口规范
    【PSR规范专题(3)】PSR-2 代码风格规范
    【PSR规范专题(2)】PSR-1 基本代码规范
    YII框架的依赖注入容器与服务定位器简述
    PHP 反射机制Reflection
    【Apache运维基础(5)】Apache的Rewrite攻略(2)
    【Apache运维基础(4)】Apache的Rewrite攻略(1)
  • 原文地址:https://www.cnblogs.com/zebinlin/p/9801094.html
Copyright © 2020-2023  润新知