diff --git a/problems/0059.螺旋矩阵II.md b/problems/0059.螺旋矩阵II.md index e46dae6d..6df8c83d 100644 --- a/problems/0059.螺旋矩阵II.md +++ b/problems/0059.螺旋矩阵II.md @@ -302,6 +302,61 @@ func generateMatrix(n int) [][]int { } ``` +Swift: + +```swift +func generateMatrix(_ n: Int) -> [[Int]] { + var result = [[Int]](repeating: [Int](repeating: 0, count: n), count: n) + + var startRow = 0 + var startColumn = 0 + var loopCount = n / 2 + let mid = n / 2 + var count = 1 + var offset = 1 + var row: Int + var column: Int + + while loopCount > 0 { + row = startRow + column = startColumn + + for c in column ..< startColumn + n - offset { + result[startRow][c] = count + count += 1 + column += 1 + } + + for r in row ..< startRow + n - offset { + result[r][column] = count + count += 1 + row += 1 + } + + for _ in startColumn ..< column { + result[row][column] = count + count += 1 + column -= 1 + } + + for _ in startRow ..< row { + result[row][column] = count + count += 1 + row -= 1 + } + + startRow += 1 + startColumn += 1 + offset += 2 + loopCount -= 1 + } + + if (n % 2) != 0 { + result[mid][mid] = count + } + return result +} +``` diff --git a/problems/0203.移除链表元素.md b/problems/0203.移除链表元素.md index a2c6e90d..9235d47e 100644 --- a/problems/0203.移除链表元素.md +++ b/problems/0203.移除链表元素.md @@ -304,6 +304,34 @@ var removeElements = function(head, val) { }; ``` +Swift: + +```swift +/** + * Definition for singly-linked list. + * public class ListNode { + * public var val: Int + * public var next: ListNode? + * public init() { self.val = 0; self.next = nil; } + * public init(_ val: Int) { self.val = val; self.next = nil; } + * public init(_ val: Int, _ next: ListNode?) { self.val = val; self.next = next; } + * } + */ +func removeElements(_ head: ListNode?, _ val: Int) -> ListNode? { + let dummyNode = ListNode() + dummyNode.next = head + var currentNode = dummyNode + while let curNext = currentNode.next { + if curNext.val == val { + currentNode.next = curNext.next + } else { + currentNode = curNext + } + } + return dummyNode.next +} +``` +