Swift 每週五題 LeetCode(7)

LULU
彼得潘的 Swift iOS App 開發教室
3 min readMar 14, 2022

--

今天是白色情人節!也是愛因斯坦的生日XD他說:『邏輯可以帶你從A到B,而想像力可以帶你去任何地方😆』沒有計劃也沒關係~靠著想象怎麼浪漫都可以~祝大家白色情人節快樂☺️

46. Permutations (Medium)

題目會給一組陣列,要列出陣列內數字的排列組合
Example 1:

Input: nums = [1,2,3]
Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
func permute(_ nums: [Int]) -> [[Int]] {
var result : [[Int]] = []
var numeros = nums

// Base case
if (nums.count == 1){
return [nums]
}

var perms : [[Int]] = []

for _ in 0..<nums.count {
let firstElement = numeros.first!
numeros.removeFirst()
// [2, 3] -> perms remove 2 -> 3
perms = permute(numeros) // 遞迴 [[3]] // [[2]] //

for i in 0..<perms.count {
perms[i].append(firstElement) // [[3,2]] // [[2,3]]
}

numeros.append(firstElement) // [3, 2]

// Add permutiations to result array
for i in 0..<perms.count {
result.append(perms[i])
}

}

return result
}

48. Rotate Image (Medium)

https://leetcode.com/problems/rotate-image/
Example 1:

Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
Output: [[7,4,1],[8,5,2],[9,6,3]]

請把圖向右轉90度:P(把每組陣列中第一個數拿出來)

func rotate(_ matrix: inout [[Int]]) {
var result: [[Int]] = []
var tempArr: [Int] = [] //暫時儲存的[]
let arrCount = matrix.count - 1

for _ in 0...arrCount {
for k in 0...arrCount { //先把第一個移除,再加回來
let arr = matrix[arrCount - k].removeFirst()
tempArr.append(arr)
}
result.append(tempArr) //最後加到二維陣列中
tempArr = []
}
matrix = result
}

49. Group Anagrams (Medium)

Given an array of strings strs, group the anagrams together. You can return the answer in any order.

An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.

Example 1:

Input: strs = ["eat","tea","tan","ate","nat","bat"]
Output: [["bat"],["nat","tan"],["ate","eat","tea"]]
func groupAnagrams(_ strs: [String]) -> [[String]] {
var result = [[String]]()
var records = [String]()
var flag = false //記錄狀態是否改變

for str in strs {
let recordItem = String(str.sorted())
flag = false
for i in 0..<records.count {
if records[i] == recordItem {
result[i].append(str)
flag = true
break
}
}
if flag == false {
result.append([str])
records.append(recordItem)
}
}
return result
}

50. Pow(x, n) (Medium)

https://leetcode.com/problems/powx-n/
這題有個偷吃步的解法XD

func myPow(_ x: Double, _ n: Int) -> Double {
return pow(x, Double(n)) // 第一個解法XD
var n = n // 第二個解法
var x = x
if n == 0 {
return 1
}
if n < 0 {
n = -n
x = 1/x
}
var ans: Double = 1
while n > 0 {
if n & 1 != 0 {
ans = ans * x
}
x = x * x
n = n >> 1
}
return ans
}

53. Maximum Subarray (Easy)

找出總和最大的連續子數組

func maxSubArray(_ nums: [Int]) -> Int {
let nums = nums
var sum = nums[0]
var current = nums[0]

for i in 1..<nums.count {
current = max(current + nums[i], nums[i])
sum = max(current, sum)
}

return sum
}

--

--

LULU
彼得潘的 Swift iOS App 開發教室

Hi👋 I’m iOS developer, I hope I can grow with you guys ☺️ Let’s learn more together.