diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 037. \345\260\217\350\241\214\346\230\237\347\242\260\346\222\236/README.md" "b/lcof2/\345\211\221\346\214\207 Offer II 037. \345\260\217\350\241\214\346\230\237\347\242\260\346\222\236/README.md" index fb3b6354cce33..f361062ea3e76 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 037. \345\260\217\350\241\214\346\230\237\347\242\260\346\222\236/README.md" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 037. \345\260\217\350\241\214\346\230\237\347\242\260\346\222\236/README.md" @@ -221,6 +221,33 @@ impl Solution { } ``` +#### Swift + +```swift +class Solution { + func asteroidCollision(_ asteroids: [Int]) -> [Int] { + var stack = [Int]() + + for asteroid in asteroids { + if asteroid > 0 { + stack.append(asteroid) + } else { + while !stack.isEmpty && stack.last! > 0 && stack.last! < -asteroid { + stack.removeLast() + } + if !stack.isEmpty && stack.last! == -asteroid { + stack.removeLast() + } else if stack.isEmpty || stack.last! < 0 { + stack.append(asteroid) + } + } + } + + return stack + } +} +``` + diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 037. \345\260\217\350\241\214\346\230\237\347\242\260\346\222\236/Solution.swift" "b/lcof2/\345\211\221\346\214\207 Offer II 037. \345\260\217\350\241\214\346\230\237\347\242\260\346\222\236/Solution.swift" new file mode 100644 index 0000000000000..3fd6956a8a3f0 --- /dev/null +++ "b/lcof2/\345\211\221\346\214\207 Offer II 037. \345\260\217\350\241\214\346\230\237\347\242\260\346\222\236/Solution.swift" @@ -0,0 +1,22 @@ +class Solution { + func asteroidCollision(_ asteroids: [Int]) -> [Int] { + var stack = [Int]() + + for asteroid in asteroids { + if asteroid > 0 { + stack.append(asteroid) + } else { + while !stack.isEmpty && stack.last! > 0 && stack.last! < -asteroid { + stack.removeLast() + } + if !stack.isEmpty && stack.last! == -asteroid { + stack.removeLast() + } else if stack.isEmpty || stack.last! < 0 { + stack.append(asteroid) + } + } + } + + return stack + } +} \ No newline at end of file