From 40c0b5b4400e860ff88afb3ccd7801ef1f5c4ff1 Mon Sep 17 00:00:00 2001 From: Lanre Adedara Date: Thu, 6 Jun 2024 06:23:29 +0100 Subject: [PATCH] feat: add swift implementation to lcof2 problem: No.037 --- .../README.md" | 27 +++++++++++++++++++ .../Solution.swift" | 22 +++++++++++++++ 2 files changed, 49 insertions(+) create mode 100644 "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" 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