[LeetCode one question per day] [Medium]406. Rebuild the queue based on height

[LeetCode one question per day] [Medium]406. Rebuild the queue based on height

406. Rebuild the queue based on height

406. Rebuild the queue based on height

Algorithm idea: array, sort

topic:

Insert picture description here

There are two ways of thinking:
1. From low to high, people with low height should leave a space k, and find the last position.
2. With height from high to bottom, tall people should stand first, and those who are short should insert k.

java code

From low to high:

  1. Sorting: height is in order from low to high; k value is in order from big to small
  2. Traverse people, use the person's k to find the position; k is what, leave a few vacancies in front;
  3. The empty position is reserved for people who are taller than him or people who are as high as him but have a lower k value than him;
  4. After traversing a person, this person has found the final position;
class Solution {
    
    
    public int[][] reconstructQueue(int[][] people) {
    
    
		//按照身高升序排列(从低到高),身高相同,k值大的排在前面
		Arrays.sort(people, new Comparator<int[]>() {
    
    
			public int compare(int[] o1, int[] o2) {
    
    
				if (o1[0] != o2[0]) {
    
    
					return o1[0] - o2[0];//身高升序
				}
				else {
    
    
					return o2[1] - o1[1];//相同,k大的排在前面
				}
			}
		});
		int n = people.length;
		int[][] res = new int[n][];//存放答案
		for (int[] p : people) {
    
    //遍历人(k值是降序)
			int count = p[1];//记录k值,用来留空位
			for (int i = 0; i < n; i++) {
    
    //一个个查找,空位表示更高或者一样高但k更小的人
				if (res[i] == null) {
    
    //遇见一个空位,count--
					count--;		
				}
				if (count == -1) {
    
    //为-1是表示没有空位需要留了,此时,i就是这个人p最后放置的位置
					res[i] = p;
					break;
				}
			}			
		}
		return res;
    }
}

From high to low:

  1. Sorting: The height is in the order from low to high; the k value is in the order of small to large
  2. Traverse people, use people to insert; k is how many, just insert it into several places;
  3. After inserting into the field, it means that the person with k people in front meets the condition;
class Solution {
    
    
    public int[][] reconstructQueue(int[][] people) {
    
    
    //按照身高升序排列(从高到低),身高相同,k值小的排在前面
		Arrays.sort(people, new Comparator<int[]>() {
    
    
			public int compare(int[] o1, int[] o2) {
    
    
				if (o1[0] != o2[0]) {
    
    
					return o2[0] - o1[0];
				}
				else {
    
    
					return o1[1] - o2[1];
				}
			}
		});
        //利用list更好的实现插入
		List<int[]> res = new LinkedList<int[]>();
		for (int[] p : people) {
    
    
			res.add(p[1], p);//插入到k个位置上
		}
		return res.toArray(new int[res.size()][2]);//返回新数组
    }
}

Guess you like

Origin blog.csdn.net/qq_39457586/article/details/109723594