自己想的这个 时间、空间上都很低 = = 。。 无语

func dailyTemperatures(_ temperatures: [Int]) -> [Int] {
var day = 0
var array = Array<Int>()
let len = temperatures.count
for i in 0..<(len - 1){
let num1 = temperatures[i]
day = 0
var exit = false
for j in (i+1)..<len {
let num2 = temperatures[j]
day += 1
if num2 > num1 {
exit = true
array.append(day)
break
}
}
if !exit {
array.append(0)
}
}
array.append(0)
return array
}
然后就是单调栈了。。 还挺奇妙的。。
func dailyTemperatures(_ temperatures: [Int]) -> [Int] {
let len = temperatures.count
if len == 1 {
return [0]
}
var array = Array<Int>(repeating: 0, count: len)
var stack = Array<Int>()
var i = 0
while( i < temperatures.count){
if stack.isEmpty || temperatures[i] <= temperatures[stack.last!]{
stack.append(i)
i += 1
}
else {
let index = stack.popLast()!
array[index] = i - index
}
}
return array
}
网友评论