go语言实战-1023-根据身高重建队列
实战
假设有打乱顺序的一群人站成一个队列。 每个人由一个整数对 (h, k) 表示,其中 h 是这个人的身高,k 是应该排在这个人前面且身高大于或等于 h 的人数。 例如:[5,2] 表示前面应该有2 个身高大于等于 5 的人,而 [5,0] 表示前面不应该存在身高大于等于 5 的人。
编写一个算法,根据每个人的身高 h 重建这个队列,使之满足每个整数对 (h, k) 中对人数 k 的要求
示列: 输入:[[7,0], [4,4], [7,1], [5,0], [6,1], [5,2]] 输出:[[5,0], [7,0], [5,2], [6,1], [4,4], [7,1]]
解题思路 首先对数组进行排序,第一个元素从高到低,如果第一个元素相同,第二个元素从高到低排序。即高个子先站前面,低个子再根据切片第二个值来插入到正确的位置。
接着进行如下操作来将低个子插入正确位置
package main
import “fmt” import “sort”
type S [][]int
func sortS(s S){ sort.Sort(s) }
func (s S) Swap(i,j int) { s[i],s[j]=s[j],s[i] }
func (s S) Len() int{ return len(s) }
func (s S) Less(i,j int) bool{ // 高的人先排,同样高的k值小的在前面 return s[i][0]>s[j][0] || (s[i][0]==s[j][0] && s[i][1]<s[j][1]) }
func reconstructQueue(people [][]int) [][]int { var res [][]int sortS(people)//先排序 for key,value:=range people { if value[1] < key { // 插入index位置 index:=value[1] // append支持两个切片,第二个切片后面要加 … temp:=append([][]int{},res[index:]…) res=append(res[0:index],value) res=append(res,temp…) } else { res=append(res,value) //直接插入res尾部 } } return res }
func main() { people := [][]int{ {9, 0}, {7, 0}, {1, 9}, {3, 0}, {2, 7}, {5, 3}, {6, 0}, {3, 4}, {6, 2}, {5, 2}} fmt.Println(“Hello, World!”, reconstructQueue(people))
}
问题一、append的问题
append 一个空成员,会让切片变化不? (切片不能比较 == ) 把 []int{} 当做一个空切片来对待,并不是一个切片的空成员 前面append一个空切片只能产生如下变化 后面append一个空切片不产生变化
func main() { test := []int{1, 2, 3} fmt.Println(test, len(test), cap(test)) test = append([]int{}, test...) fmt.Println(test, len(test), cap(test)) test = append([]int{}, test...) fmt.Println(test, len(test), cap(test)) test1 := []int{1, 2, 3, 4} fmt.Println(test, len(test1), cap(test1)) test1 = append([]int{}, test1...) fmt.Println(test1, len(test1), cap(test1)) } [1 2 3] 3 3 [1 2 3] 3 4 [1 2 3] 3 4 [1 2 3 4] 4 4 [1 2 3 4] 4 4
func main() { test := []int{1, 2, 3} fmt.Println(test, len(test), cap(test)) test = append(test, []int{}...) fmt.Println(test, len(test), cap(test)) } [1 2 3] 3 3 [1 2 3] 3 3
问题二、二维切片的问题
初始化: res := make([][length]int, length) 例如: res := make([][2]int, 10) fmt.Println(res) 输出: [[0 0] [0 0] [0 0] [0 0] [0 0] [0 0] [0 0] [0 0] [0 0] [0 0]] 或者 a := [][]float64{ {1, 2, 3, 4}, {12, 21, 3, 14}, {1, 1, 2, 3}, {2, 3, 1, 6}, {2, 2, 3, 3}, {1, 1, 1, 1}}
问题三、排序
func main() { people := [][]int{ {9, 0}, {7, 0}, {1, 9}, {3, 0}, {2, 7}, {5, 3}, {6, 0}, {3, 4}, {6, 2}, {5, 2}} less := func(i, j int) bool { if people[i][0] == people[j][0] { return people[i][1] >= people[j][1] } return people[i][0] > people[j][0] } greater := func(i, j int) bool { if people[i][0] == people[j][0] { return people[i][1] <= people[j][1] } return people[i][0] < people[j][0] } sort.Slice(people, less) fmt.Println(people) sort.Slice(people, greater) fmt.Println(people) }