406.根据身高重建队列

43 阅读1分钟

题目:
假设有打乱顺序的一群人站成一个队列,数组 people 表示队列中一些人的属性(不一定按顺序)。每个 people[i] = [hi, ki] 表示第 i 个人的身高为 hi ,前面 正好 有 ki 个身高大于或等于 hi 的人。

请你重新构造并返回输入数组 people 所表示的队列。返回的队列应该格式化为数组 queue ,其中 queue[j] = [hj, kj] 是队列中第 j 个人的属性(queue[0] 是排在队列前面的人)。
算法:
不戳针不辍 image.png

func reconstructQueue(people [][]int) [][]int {
	sort.Slice(people, func(i, j int) bool {
		if people[i][0] < people[j][0] {
			return true
		}
		if people[i][0] == people[j][0] && people[i][1] < people[j][1] {
			return true
		}
		return false
	})

	i := len(people) - 1
	for i >= 0 {
		if people[i][1] != 0 {
			// 找到相同身高的people数n
			n := 0
			k := i 
			for k - 1 >= 0 && people[k - 1][0] == people[k][0] {
				n++
				k--
			}
			
			for n >= 0 {
				tmp := people[i]
				j, count := i, people[i][1] - n
				for j + 1 < len(people) && count > 0 {
					people[j] = people[j + 1]
					j++
					count--
				}
				people[j] = tmp
				n --
				i --
			}

		} else {
			i--
		}
		
	}
	return people
}