为数组篇 增加 Swift 实现

pull/34/head
zhenzi 2021-07-17 12:13:15 +08:00
parent 2c4afffbd3
commit c14c2297f1
14 changed files with 702 additions and 1 deletions

View File

@ -114,5 +114,45 @@ class Solution:
ans = max(ans, t)
return ans
```
Swift Code
```swift
class Solution {
func maxSatisfied(_ customers: [Int], _ grumpy: [Int], _ minutes: Int) -> Int {
let len = customers.count
var winSum = 0, rightSum = 0, leftSum = 0
// 右区间的值
for i in minutes..<len {
if grumpy[i] == 0 {
rightSum += customers[i]
}
}
// 窗口的值
for i in 0..<minutes {
winSum += customers[i]
}
var maxCustomer = winSum + leftSum + rightSum
// 窗口左边缘
var left = 1, right = minutes
while right < len {
// 重新计算左区间的值,也可以用 customer 值和 grumpy 值相乘获得
if grumpy[left - 1] == 0 {
leftSum += customers[left - 1]
}
// 重新计算右区间值
if grumpy[right] == 0 {
rightSum -= customers[right]
}
// 窗口值
winSum = winSum - customers[left - 1] + customers[right]
maxCustomer = max(maxCustomer, winSum + leftSum + rightSum) // 保留最大值
// 移动窗口
left += 1
right += 1
}
return maxCustomer
}
}
```

View File

@ -111,3 +111,152 @@ class Solution:
return maxwin
```
Swift Code
Swift58 / 61
```swift
class Solution {
func longestSubarray(_ nums: [Int], _ limit: Int) -> Int {
var maxQueue:[Int] = []
var minQueue:[Int] = []
let len = nums.count
var right = 0, left = 0, maxWin = 0
while right < len {
while !maxQueue.isEmpty && (maxQueue.last! < nums[right]) {
maxQueue.removeLast()
}
while !minQueue.isEmpty && (minQueue.last! > nums[right]) {
minQueue.removeLast()
}
maxQueue.append(nums[right])
minQueue.append(nums[right])
while (maxQueue.first! - minQueue.first!) > limit {
if maxQueue.first! == nums[left] {
maxQueue.removeFirst()
}
if minQueue.first! == nums[left] {
minQueue.removeFirst()
}
left += 1
}
maxWin = max(maxWin, right - left + 1)
right += 1
}
return maxWin
}
}
```
Swift使100.00%
```swift
class Solution {
func longestSubarray(_ nums: [Int], _ limit: Int) -> Int {
var maxQueue = Deque<Int>.init()
var minQueue = Deque<Int>.init()
let len = nums.count
var right = 0, left = 0, maxWin = 0
while right < len {
while !maxQueue.isEmpty && (maxQueue.peekBack()! < nums[right]) {
maxQueue.dequeueBack()
}
while !minQueue.isEmpty && (minQueue.peekBack()! > nums[right]) {
minQueue.dequeueBack()
}
maxQueue.enqueue(nums[right])
minQueue.enqueue(nums[right])
while (maxQueue.peekFront()! - minQueue.peekFront()!) > limit {
if maxQueue.peekFront()! == nums[left] {
maxQueue.dequeue()
}
if minQueue.peekFront()! == nums[left] {
minQueue.dequeue()
}
left += 1
}
maxWin = max(maxWin, right - left + 1)
right += 1
}
return maxWin
}
// 双端队列数据结构
public struct Deque<T> {
private var array: [T?]
private var head: Int
private var capacity: Int
private let originalCapacity: Int
public init(_ capacity: Int = 10) {
self.capacity = max(capacity, 1)
originalCapacity = self.capacity
array = [T?](repeating: nil, count: capacity)
head = capacity
}
public var isEmpty: Bool {
return count == 0
}
public var count: Int {
return array.count - head
}
public mutating func enqueue(_ element: T) {
array.append(element)
}
public mutating func enqueueFront(_ element: T) {
if head == 0 {
capacity *= 2
let emptySpace = [T?](repeating: nil, count: capacity)
array.insert(contentsOf: emptySpace, at: 0)
head = capacity
}
head -= 1
array[head] = element
}
public mutating func dequeue() -> T? {
guard head < array.count, let element = array[head] else { return nil }
array[head] = nil
head += 1
if capacity >= originalCapacity && head >= capacity*2 {
let amountToRemove = capacity + capacity/2
array.removeFirst(amountToRemove)
head -= amountToRemove
capacity /= 2
}
return element
}
public mutating func dequeueBack() -> T? {
if isEmpty {
return nil
} else {
return array.removeLast()
}
}
public func peekFront() -> T? {
if isEmpty {
return nil
} else {
return array[head]
}
}
public func peekBack() -> T? {
if isEmpty {
return nil
} else {
return array.last!
}
}
}
}
```

View File

@ -76,6 +76,32 @@ class Solution:
return rearr
```
Swift Code:
```swift
class Solution {
func twoSum(_ nums: [Int], _ target: Int) -> [Int] {
let count = nums.count
if count < 2 {
return [0]
}
var rearr: [Int] = []
// 查询元素
for i in 0..<count {
for j in i+1..<count {
// 发现符合条件情况
if nums[i] + nums[j] == target {
rearr.append(i)
rearr.append(j)
}
}
}
return rearr
}
}
```
****
****
@ -159,3 +185,20 @@ class Solution:
return [0]
```
Swift Code:
```swift
class Solution {
func twoSum(_ nums: [Int], _ target: Int) -> [Int] {
var m:[Int:Int] = [:]
for i in 0..<nums.count {
let n = nums[i]
if let k = m[target - n] { // 如果存在则返回
return [k, i]
}
m[n] = i // 不存在则存入
}
return [0]
}
}
```

View File

@ -78,6 +78,32 @@ class Solution:
return False
```
Swift Code
```swift
class Solution {
func containsNearbyDuplicate(_ nums: [Int], _ k: Int) -> Bool {
if nums.count == 0 {
return false
}
var dict:[Int:Int] = [:]
for i in 0..<nums.count {
// 如果含有
if let v = dict[nums[i]] {
// 判断是否小于K如果小于等于则直接返回
let abs = abs(i - v)
if abs <= k {
return true
}
}
// 更新索引,此时有两种情况,不存在,或者存在时,将后出现的索引保存
dict[nums[i]] = i
}
return false
}
}
```
**HashSet**
****
@ -140,3 +166,28 @@ class Solution:
s.remove(nums[i - k])
return False
```
Swift Code
```swift
class Solution {
func containsNearbyDuplicate(_ nums: [Int], _ k: Int) -> Bool {
if nums.count == 0 {
return false
}
var set:Set<Int> = []
for i in 0..<nums.count {
// 含有该元素返回true
if set.contains(nums[i]) {
return true
}
// 添加新元素
set.insert(nums[i])
if set.count > k {
set.remove(nums[i - k])
}
}
return false
}
}
```

View File

@ -164,3 +164,23 @@ public:
};
```
Swift Code
```swift
class Solution {
func removeElement(_ nums: inout [Int], _ val: Int) -> Int {
if nums.count == 0 {
return 0
}
var i = 0
for j in 0..<nums.count {
if nums[j] != val {
nums[i] = nums[j]
i += 1
}
}
return i
}
}
```

View File

@ -89,6 +89,33 @@ class Solution:
return len(res)
```
Swift Code
```swift
class Solution {
func firstMissingPositive(_ nums: [Int]) -> Int {
if nums.count == 0 {
return 1
}
// 因为是返回第一个正整数,不包括 0所以需要长度加1细节1
var res:[Int] = Array.init(repeating: 0, count: nums.count + 1)
// 将数组元素添加到辅助数组中
for x in nums {
if x > 0 && x < res.count {
res[x] = x
}
}
// 遍历查找,发现不一样时直接返回
for i in 1..<res.count {
if res[i] != i {
return i
}
}
// 缺少最后一个,例如 123此时缺少 4 细节2
return res.count
}
}
```
使使 nums 使
@ -166,3 +193,42 @@ class Solution:
return n + 1
```
Swift Code
```swift
class Solution {
func firstMissingPositive(_ nums: [Int]) -> Int {
var nums = nums
let len = nums.count
if len == 0 {
return 1
}
// 遍历数组
for i in 0..<len {
// 需要考虑指针移动情况大于0小于len+1不等与i+1
// 两个交换的数相等时,防止死循环
while nums[i] > 0
&& nums[i] < len + 1
&& nums[i] != i + 1
&& nums[i] != nums[nums[i] - 1]
{
//nums.swapAt(i, (nums[i] - 1)) // 系统方法
self.swap(&nums, i, (nums[i] - 1)) // 自定义方法
}
}
// 遍历寻找缺失的正整数
for i in 0..<len {
if nums[i] != i + 1 {
return i + 1
}
}
return len + 1
}
func swap(_ nums: inout [Int], _ i: Int, _ j: Int) {
let temp = nums[i]
nums[i] = nums[j]
nums[j] = temp
}
}
```

View File

@ -84,6 +84,32 @@ class Solution:
return max(maxcount, right - left)
```
Swift Code
```swift
class Solution {
func findMaxConsecutiveOnes(_ nums: [Int]) -> Int {
var left = 0, right = 0, res = 0
let len = nums.count
while right < len {
if nums[right] == 1 {
right += 1
continue
}
// 保存最大值
res = max(res, right - left)
// 跳过 0 的情况
while right < len && nums[right] == 0 {
right += 1
}
// 同一起点继续遍历
left = right
}
return max(res, right - left)
}
}
```
@ -132,3 +158,22 @@ class Solution:
return ans
```
Swift Code
```swift
class Solution {
func findMaxConsecutiveOnes(_ nums: [Int]) -> Int {
let len = nums.count
var maxCount = 0, count = 0
for i in 0..<len {
if nums[i] == 1 {
count += 1
} else { // 这里可以改成 while
maxCount = max(maxCount, count)
count = 0
}
}
return max(maxCount, count)
}
}
```

View File

@ -120,5 +120,40 @@ class Solution:
return arr
```
Swift Code
```swift
class Solution {
func spiralOrder(_ matrix: [[Int]]) -> [Int] {
var arr:[Int] = []
var left = 0, right = matrix[0].count - 1
var top = 0, down = matrix.count - 1
while (true) {
for i in left...right {
arr.append(matrix[top][i])
}
top += 1
if top > down { break }
for i in top...down {
arr.append(matrix[i][right])
}
right -= 1
if left > right { break}
for i in stride(from: right, through: left, by: -1) {
arr.append(matrix[down][i])
}
down -= 1
if top > down { break}
for i in stride(from: down, through: top, by: -1) {
arr.append(matrix[i][left])
}
left += 1
if left > right { break}
}
return arr
}
}
```

View File

@ -45,6 +45,8 @@ class Solution {
Python3
Swift
使西
![](https://cdn.jsdelivr.net/gh/tan45du/github.io.phonto2@master/myphoto/微信截图_20210113193831.4wk2b9zc8vm0.png)
@ -160,3 +162,27 @@ class Solution {
}
```
Swift Code
```swift
class Solution {
func subarraySum(_ nums: [Int], _ k: Int) -> Int {
if nums.count == 0 {
return 0
}
var map: [Int: Int] = [:]
map[0] = 1 // 需要添加入一个元素垫底,已支持前几位就满足的情况
var presum = 0, count = 0
for x in nums {
presum += x
//当前前缀和已知,判断是否含有 presum - k的前缀和那么我们就知道某一区间的和为 k 了。
if let v = map[presum - k] {
count += v //获取presum-k前缀和出现次数
}
map[presum] = (map[presum] ?? 0) + 1
}
return count
}
}
```

View File

@ -140,6 +140,43 @@ class Solution:
return arr
```
Swift Code:
```swift
class Solution {
func spiralOrder(_ matrix: [[Int]]) -> [Int] {
var arr:[Int] = []
var left = 0, right = matrix[0].count - 1
var top = 0, down = matrix.count - 1
while (true) {
for i in left...right {
arr.append(matrix[top][i])
}
top += 1
if top > down { break }
for i in top...down {
arr.append(matrix[i][right])
}
right -= 1
if left > right { break}
for i in stride(from: right, through: left, by: -1) {
arr.append(matrix[down][i])
}
down -= 1
if top > down { break}
for i in stride(from: down, through: top, by: -1) {
arr.append(matrix[i][left])
}
left += 1
if left > right { break}
}
return arr
}
}
```
54 ,
Java Code:
@ -226,3 +263,45 @@ class Solution:
return arr.tolist()
```
Swift Code:
```swift
class Solution {
func generateMatrix(_ n: Int) -> [[Int]] {
var arr:[[Int]] = Array.init(repeating: Array.init(repeating: 0, count: n), count: n)
var left = 0, right = n - 1
var top = 0, bottom = n - 1
var num = 1, numSize = n * n
while true {
for i in left...right {
arr[top][i] = num
num += 1
}
top += 1
if num > numSize { break}
for i in top...bottom {
arr[i][right] = num
num += 1
}
right -= 1
if num > numSize { break}
for i in stride(from: right, through: left, by: -1) {
arr[bottom][i] = num
num += 1
}
bottom -= 1
if num > numSize { break}
for i in stride(from: bottom, through: top, by: -1) {
arr[i][left] = num
num += 1
}
left += 1
if num > numSize { break}
}
return arr
}
}
```

View File

@ -85,3 +85,23 @@ class Solution:
arr[0] = 1
return arr
```
Swift Code:
```swift
class Solution {
func plusOne(_ digits: [Int]) -> [Int] {
let count = digits.count
var digits = digits
for i in stride(from: count - 1, through: 0, by: -1) {
digits[i] = (digits[i] + 1) % 10
if digits[i] != 0 {
return digits
}
}
var arr: [Int] = Array.init(repeating: 0, count: count + 1)
arr[0] = 1
return arr
}
}
```

View File

@ -96,6 +96,38 @@ class Solution:
nums[j] = temp
```
Swift Code:
```swift
class Solution {
func sortColors(_ nums: inout [Int]) {
let count = nums.count
var left = 0, i = left, right = count - 1
while i <= right {
if nums[i] == 2 {
//nums.swapAt(i, right) 直接调用系统方法
self.swap(&nums, i, right) // 保持风格统一走自定义交换
right -= 1
} else if nums[i] == 0 {
//nums.swapAt(i, left) 直接调用系统方法
self.swap(&nums, i, left) // 保持风格统一走自定义交换
i += 1
left += 1
} else {
i += 1
}
}
}
func swap(_ nums: inout [Int], _ i: Int, _ j: Int) {
let temp = nums[i]
nums[i] = nums[j]
nums[j] = temp
}
}
```
使
[0,0,0,1,1,1,2,2,2]
@ -174,4 +206,39 @@ class Solution:
temp = nums[i]
nums[i] = nums[j]
nums[j] = temp
```
Swift Code:
```swift
class Solution {
func sortColors(_ nums: inout [Int]) {
let count = nums.count
var left = 0, i = left, right = count - 1
while i <= right {
if nums[i] == 0 {
//nums.swapAt(i, left) 直接调用系统方法
self.swap(&nums, i, left) // 保持风格统一走自定义交换
left += 1
}
if nums[i] == 2 {
//nums.swapAt(i, right) 直接调用系统方法
self.swap(&nums, i, right) // 保持风格统一走自定义交换
right -= 1
//如果不等于 1 则需要继续判断,所以不移动 i 指针i--
if nums[i] != 1 {
i -= 1
}
}
i += 1
}
}
func swap(_ nums: inout [Int], _ i: Int, _ j: Int) {
let temp = nums[i]
nums[i] = nums[j]
nums[j] = temp
}
}
```

View File

@ -61,6 +61,24 @@ class Solution:
return -1
```
Swift Code:
```swift
class Solution {
func findRepeatNumber(_ nums: [Int]) -> Int {
var set: Set<Int> = []
for n in nums {
if set.contains(n) { // 如果发现某元素存在,则返回
return n
}
set.insert(n) // 存入集合
}
return -1
}
}
```
#### ****
****
@ -136,3 +154,26 @@ class Solution:
nums[temp] = temp
return -1
```
Swift Code:
```swift
class Solution {
func findRepeatNumber(_ nums: [Int]) -> Int {
if nums.isEmpty {
return -1
}
var nums = nums;
for i in 0..<nums.count {
while nums[i] != i {
if nums[i] == nums[nums[i]] {
return nums[i]
}
nums.swapAt(i, nums[i])
}
}
return -1
}
}
```

View File

@ -106,3 +106,22 @@ class Solution:
return windowlen
```
Swift Code
```swift
class Solution {
func minSubArrayLen(_ target: Int, _ nums: [Int]) -> Int {
var sum = 0, windowlen = Int.max, i = 0
for j in 0..<nums.count {
sum += nums[j]
while sum >= target {
windowlen = min(windowlen, j - i + 1)
sum -= nums[i]
i += 1
}
}
return windowlen == Int.max ? 0 : windowlen
}
}
```