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]]
这次的题目比较简单,一次就读懂了,但比昨天的题难吧。。。反正是自己没想出来,看了一个Hints才做出来的。。。忍着jio疼写代码。。。哇,简直好想哭
这个题最重要的提示就是,先找最矮的,当有多个最矮的时候就先找最矮的里面前面比他高的最多的,因为当前最矮的,前面的空位置都是高于等于他的~
然后就看k的值数空位置,然后这个空位置就是当前人正确的位置。
1 class Solution { 2 public int[][] reconstructQueue(int[][] people) { 3 int rownum = people.length; 4 //对于people为空的时候没有特殊处理 5 if(rownum == 0) 6 return people; 7 int colnum = people[0].length; 8 int[][] newPeople = new int[rownum][colnum]; 9 int[] order = new int[people.length]; 10 //order初始化 11 for(int i = 0 ; i < order.length ; i++) 12 order[i] = -1; 13 for(int i = 0 ; i < rownum ; i++) 14 for(int j = 0 ; j < colnum ; j++) 15 newPeople[i][j] = people[i][j]; 16 for(int j = 0 ; j < order.length ; j++) { 17 int min = 999999; 18 int max = -1; 19 int mark = -1; 20 for(int i = 0 ; i < people.length ; i++) 21 { 22 //寻找最小的 23 if(people[i][0] >= 0&&people[i][0] <= min) 24 { 25 if(people[i][0] == min) 26 { 27 if(people[i][1] > max) 28 { 29 max = people[i][1]; 30 mark = i; 31 } 32 else 33 continue; 34 } 35 36 else 37 { 38 min = people[i][0]; 39 max = people[i][1]; 40 mark = i; 41 } 42 } 43 } 44 people[mark][0] = -2; 45 //找空位 46 int temp = 0; 47 int point = 0; 48 while(true) 49 { 50 if(order[point] == -1) 51 { 52 if(temp >= max) 53 break; 54 point++; 55 temp++; 56 } 57 else 58 point++; 59 } 60 order[point] = mark; 61 62 } 63 //返回值 64 for(int i = 0 ; i < rownum ; i++) 65 { 66 people[i][0] = newPeople[order[i]][0]; 67 people[i][1] = newPeople[order[i]][1]; 68 //System.out.println(people[i][0] + " " + people[i][1]); 69 } 70 return people; 71 } 72 }
哇。。。脚太疼了,我明天接着把思路什么的写完。