自己想的= =。。 因为swift的区间问题吧= =。。每次进行下一步都做了下判断。。感觉挺扯的
func spiralOrder(_ matrix: [[Int]]) -> [Int] {
var ans = [Int]()
let row = matrix.count
let col = matrix.first?.count ?? 0
var left = 0, right = col ,top = 0 ,bottom = row
while true {
if left >= right {
break
}
//从左到右
for i in left..<right {
ans.append(matrix[top][i])
}
// print(ans)
right -= 1
top += 1
if top >= bottom {
break
}
//从上到下
for i in top..<bottom {
ans.append(matrix[i][right])
}
bottom -= 1
// print(ans)
if left >= right {
break
}
//从右到左
for i in (left..<right).reversed() {
ans.append(matrix[bottom][i])
}
// print(ans)
if top >= bottom {
break
}
//从下往上
for i in (top..<bottom).reversed() {
ans.append(matrix[i][left])
}
// print(ans)
left += 1
}
return ans
}
优化版本
func spiralOrder(_ matrix: [[Int]]) -> [Int] {
var ans = [Int]()
var left = 0, right = matrix.first?.count ?? 0 ,top = 0 ,bottom = matrix.count
while true {
//从左到右
for i in left..<right {
ans.append(matrix[top][i])
}
// print(ans)
right -= 1
top += 1
if top >= bottom {
break
}
//从上到下
for i in top..<bottom {
ans.append(matrix[i][right])
}
bottom -= 1
// print(ans)
if left >= right {
break
}
//从右到左
for i in (left..<right).reversed() {
ans.append(matrix[bottom][i])
}
// print(ans)
if top >= bottom {
break
}
//从下往上
for i in (top..<bottom).reversed() {
ans.append(matrix[i][left])
}
// print(ans)
left += 1
if left >= right {
break
}
}
return ans
}
网友评论