2940. Find Building Where Alice and Bob Can Meet
思路
(1)如果queries[i][0]==queries[i][1]
那ans[i]=queries[i][0]
(2)
假设queries[i][0]>queries[j][0]且heights[queries[i][0]]>heights[queries[0][1]]
那ans[i]=queries[i][0]
(3)
找到heights[j]>max(heights[queries[i][0]] , heights[queries[0][1]])
且j>max(queries[i][0],queries[i][1])
假设heights的长度为n
先把所有queries[i]变成queries[i][0] < queries[i][1]的形式
将queries按照queries[i][1]的大小由大排到小
并建立increasing monotonic stack
从queries[0]开始
把heights[j](j=n-1~queries[i][1])全部push进到stack里面
接着判断是(1)、(2)、(3)哪一种情况,(1)、(2)就照做
(3)的话就用二分搜寻法去stack里面找
这样就能得到答案了
golang code:
func leftmostBuildingQueries(heights []int, queries [][]int) []int {
ans, idx := make([]int, len(queries)), make([]int, len(queries))
for key := range idx {
if queries[key][0] > queries[key][1] {
queries[key][0], queries[key][1] = queries[key][1], queries[key][0]
}
idx[key] = key
}
slices.SortFunc(idx, func(i, j int) int { return queries[j][1] - queries[i][1
] })
stack := []int{}
j := len(heights) - 1
for _, val := range idx {
x, y := queries[val][0], queries[val][1]
if y == x || heights[y] > heights[x] {
ans[val] = y
} else {
for ; j > y; j