Skip to content

feat: add swift implementation to lcof problem: No.51 #2936

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
May 28, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
57 changes: 57 additions & 0 deletions lcof/面试题51. 数组中的逆序对/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -312,6 +312,63 @@ public class Solution {
}
```

#### Swift

```swift
class Solution {
private var nums: [Int] = []
private var temp: [Int] = []

func reversePairs(_ nums: [Int]) -> Int {
self.nums = nums
let n = nums.count
self.temp = [Int](repeating: 0, count: n)
return mergeSort(0, n - 1)
}

private func mergeSort(_ left: Int, _ right: Int) -> Int {
if left >= right {
return 0
}
let mid = (left + right) / 2
var count = mergeSort(left, mid) + mergeSort(mid + 1, right)
var i = left
var j = mid + 1
var k = left

while i <= mid && j <= right {
if nums[i] <= nums[j] {
temp[k] = nums[i]
i += 1
} else {
count += mid - i + 1
temp[k] = nums[j]
j += 1
}
k += 1
}

while i <= mid {
temp[k] = nums[i]
i += 1
k += 1
}

while j <= right {
temp[k] = nums[j]
j += 1
k += 1
}

for i in left...right {
nums[i] = temp[i]
}

return count
}
}
```

<!-- tabs:end -->

<!-- solution:end -->
Expand Down
52 changes: 52 additions & 0 deletions lcof/面试题51. 数组中的逆序对/Solution.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
class Solution {
private var nums: [Int] = []
private var temp: [Int] = []

func reversePairs(_ nums: [Int]) -> Int {
self.nums = nums
let n = nums.count
self.temp = [Int](repeating: 0, count: n)
return mergeSort(0, n - 1)
}

private func mergeSort(_ left: Int, _ right: Int) -> Int {
if left >= right {
return 0
}
let mid = (left + right) / 2
var count = mergeSort(left, mid) + mergeSort(mid + 1, right)
var i = left
var j = mid + 1
var k = left

while i <= mid && j <= right {
if nums[i] <= nums[j] {
temp[k] = nums[i]
i += 1
} else {
count += mid - i + 1
temp[k] = nums[j]
j += 1
}
k += 1
}

while i <= mid {
temp[k] = nums[i]
i += 1
k += 1
}

while j <= right {
temp[k] = nums[j]
j += 1
k += 1
}

for i in left...right {
nums[i] = temp[i]
}

return count
}
}