mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 03:34:02 +08:00
@ -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
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
@ -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
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
Reference in New Issue
Block a user