update 0406.根据身高重建队列: 优化 go 代码

This commit is contained in:
Yuhao Ju
2022-12-17 00:36:31 +08:00
committed by GitHub
parent b6a92c387e
commit c8b5ca8caa

View File

@ -39,7 +39,7 @@
## 思路
本题有两个维度h和k看到这种题目一定要想如何确定一个维度然后按照另一个维度重新排列
本题有两个维度h和k看到这种题目一定要想如何确定一个维度然后按照另一个维度重新排列
其实如果大家认真做了[135. 分发糖果](https://programmercarl.com/0135.分发糖果.html)就会发现和此题有点点的像
@ -47,7 +47,7 @@
**如果两个维度一起考虑一定会顾此失彼**
对于本题相信大家困惑的点是先确定k还是先确定h呢也就是究竟先按h排序呢还先按照k排序呢
对于本题相信大家困惑的点是先确定k还是先确定h呢也就是究竟先按h排序呢先按照k排序呢
如果按照k来从小到大排序排完之后会发现k的排列并不符合条件身高也不符合条件两个维度哪一个都没确定下来
@ -222,48 +222,46 @@ class Solution:
### Go
```go
func reconstructQueue(people [][]int) [][]int {
//先将身高从大到小排序,确定最大个子的相对位置
sort.Slice(people,func(i,j int)bool{
if people[i][0]==people[j][0]{
return people[i][1]<people[j][1]//这个才是当身高相同时将K按照从小到大排序
// 先将身高从大到小排序,确定最大个子的相对位置
sort.Slice(people, func(i, j int) bool {
if people[i][0] == people[j][0] {
return people[i][1] < people[j][1] // 当身高相同时将K按照从小到大排序
}
return people[i][0]>people[j][0]//这个只是确保身高按照由大到小的顺序来排并不确定K是按照从小到大排序的
return people[i][0] > people[j][0] // 身高按照由大到小的顺序来排
})
//再按照K进行插入排序优先插入K小的
result := make([][]int, 0)
for _, info := range people {
result = append(result, info)
copy(result[info[1] +1:], result[info[1]:])//将插入位置之后的元素后移动一位(意思是腾出空间)
result[info[1]] = info//将插入元素位置插入元素
// 再按照K进行插入排序优先插入K小的
for i, p := range people {
copy(people[p[1]+1 : i+1], people[p[1] : i+1]) // 空出一个位置
people[p[1]] = p
}
return result
return people
}
```
```go
//链表
// 链表实现
func reconstructQueue(people [][]int) [][]int {
sort.Slice(people,func (i,j int) bool {
if people[i][0]==people[j][0]{
return people[i][1]<people[j][1]//当身高相同时将K按照从小到大排序
if people[i][0] == people[j][0] {
return people[i][1] < people[j][1] //当身高相同时将K按照从小到大排序
}
//先将身高从大到小排序,确定最大个子的相对位置
return people[i][0]>people[j][0]
return people[i][0] > people[j][0]
})
l:=list.New()//创建链表
for i:=0;i<len(people);i++{
position:=people[i][1]
mark:=l.PushBack(people[i])//插入元素
e:=l.Front()
for position!=0{//获取相对位置
l := list.New() //创建链表
for i:=0; i < len(people); i++ {
position := people[i][1]
mark := l.PushBack(people[i]) //插入元素
e := l.Front()
for position != 0 { //获取相对位置
position--
e=e.Next()
e = e.Next()
}
l.MoveBefore(mark,e)//移动位置
l.MoveBefore(mark, e) //移动位置
}
res:=[][]int{}
for e:=l.Front();e!=nil;e=e.Next(){
res=append(res,e.Value.([]int))
res := [][]int{}
for e := l.Front(); e != nil; e = e.Next() {
res = append(res, e.Value.([]int))
}
return res
}