Skip to content

Commit f89775d

Browse files
committed
Added tasks 41-148
1 parent cc4ca68 commit f89775d

File tree

44 files changed

+3709
-3
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

44 files changed

+3709
-3
lines changed

README.md

+123
Large diffs are not rendered by default.

src/main/swift/g0001_0100/s0002_add_two_numbers/readme.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,7 @@ To solve the Add Two Numbers problem in Swift using a `Solution` class, we'll fo
5353
Here's the implementation:
5454

5555
```swift
56-
/*
56+
/**
5757
* Definition for singly-linked list.
5858
* public class ListNode {
5959
* public var val: Int

src/main/swift/g0001_0100/s0024_swap_nodes_in_pairs/readme.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,7 @@ To solve the "Swap Nodes in Pairs" problem in Swift with a `Solution` class, we
5050
Here's the implementation:
5151

5252
```swift
53-
/*
53+
/**
5454
* Definition for singly-linked list.
5555
* public class ListNode {
5656
* public var val: Int

src/main/swift/g0001_0100/s0025_reverse_nodes_in_k_group/readme.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -66,7 +66,7 @@ To solve the "Reverse Nodes in k-Group" problem in Swift with a `Solution` class
6666
Here's the implementation:
6767

6868
```swift
69-
/*
69+
/**
7070
* Definition for singly-linked list.
7171
* public class ListNode {
7272
* public var val: Int
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
[![](https://img.shields.io/github/stars/LeetCode-in-Swift/LeetCode-in-Swift?label=Stars&style=flat-square)](https://github.com/LeetCode-in-Swift/LeetCode-in-Swift)
2+
[![](https://img.shields.io/github/forks/LeetCode-in-Swift/LeetCode-in-Swift?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/LeetCode-in-Swift/LeetCode-in-Swift/fork)
3+
4+
## 41\. First Missing Positive
5+
6+
Hard
7+
8+
Given an unsorted integer array `nums`, return the smallest missing positive integer.
9+
10+
You must implement an algorithm that runs in `O(n)` time and uses constant extra space.
11+
12+
**Example 1:**
13+
14+
**Input:** nums = [1,2,0]
15+
16+
**Output:** 3
17+
18+
**Example 2:**
19+
20+
**Input:** nums = [3,4,-1,1]
21+
22+
**Output:** 2
23+
24+
**Example 3:**
25+
26+
**Input:** nums = [7,8,9,11,12]
27+
28+
**Output:** 1
29+
30+
**Constraints:**
31+
32+
* <code>1 <= nums.length <= 5 * 10<sup>5</sup></code>
33+
* <code>-2<sup>31</sup> <= nums[i] <= 2<sup>31</sup> - 1</code>
34+
35+
To solve the "First Missing Positive" problem in Swift with a `Solution` class, we can follow these steps:
36+
37+
1. Define a `Solution` class.
38+
2. Define a method named `firstMissingPositive` that takes an array of integers `nums` as input and returns the smallest missing positive integer.
39+
3. Iterate through the array and mark the positive integers found by negating the value at the corresponding index.
40+
4. Iterate through the modified array again and return the index of the first positive number (which is the smallest missing positive integer).
41+
5. If no positive number is found, return `nums.length + 1`.
42+
43+
Here's the implementation:
44+
45+
```swift
46+
public class Solution {
47+
public func firstMissingPositive(_ nums: [Int]) -> Int {
48+
var nums = nums
49+
for i in 0..<nums.count {
50+
while nums[i] > 0 && nums[i] <= nums.count && nums[i] != i + 1 {
51+
let val = nums[i]
52+
if nums[val - 1] == val {
53+
break
54+
}
55+
nums.swapAt(i, val - 1)
56+
}
57+
}
58+
for i in 0..<nums.count {
59+
if nums[i] != i + 1 {
60+
return i + 1
61+
}
62+
}
63+
return nums.count + 1
64+
}
65+
}
66+
```
67+
68+
This implementation provides a solution to the "First Missing Positive" problem in Swift. It marks positive integers found by negating the value at the corresponding index and then iterates through the modified array to find the smallest missing positive integer. If no positive number is found, it returns `nums.length + 1`.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
[![](https://img.shields.io/github/stars/LeetCode-in-Swift/LeetCode-in-Swift?label=Stars&style=flat-square)](https://github.com/LeetCode-in-Swift/LeetCode-in-Swift)
2+
[![](https://img.shields.io/github/forks/LeetCode-in-Swift/LeetCode-in-Swift?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/LeetCode-in-Swift/LeetCode-in-Swift/fork)
3+
4+
## 42\. Trapping Rain Water
5+
6+
Hard
7+
8+
Given `n` non-negative integers representing an elevation map where the width of each bar is `1`, compute how much water it can trap after raining.
9+
10+
**Example 1:**
11+
12+
![](https://assets.leetcode.com/uploads/2018/10/22/rainwatertrap.png)
13+
14+
**Input:** height = [0,1,0,2,1,0,1,3,2,1,2,1]
15+
16+
**Output:** 6
17+
18+
**Explanation:** The above elevation map (black section) is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped.
19+
20+
**Example 2:**
21+
22+
**Input:** height = [4,2,0,3,2,5]
23+
24+
**Output:** 9
25+
26+
**Constraints:**
27+
28+
* `n == height.length`
29+
* <code>1 <= n <= 2 * 10<sup>4</sup></code>
30+
* <code>0 <= height[i] <= 10<sup>5</sup></code>
31+
32+
To solve the "Trapping Rain Water" problem in Swift with a `Solution` class, we can follow these steps:
33+
34+
1. Define a `Solution` class.
35+
2. Define a method named `trap` that takes an array of integers `height` as input and returns the amount of water it can trap after raining.
36+
3. Initialize two pointers `left` and `right` at the beginning and end of the array respectively.
37+
4. Initialize two variables `leftMax` and `rightMax` to keep track of the maximum height of bars encountered from the left and right directions respectively.
38+
5. Iterate through the array using the two pointers:
39+
- Update `leftMax` as the maximum of `leftMax` and `height[left]`.
40+
- Update `rightMax` as the maximum of `rightMax` and `height[right]`.
41+
- If `height[left] < height[right]`, calculate the water trapped at the current position using `leftMax` and subtract the height of the current bar. Move `left` pointer to the right.
42+
- Otherwise, calculate the water trapped at the current position using `rightMax` and subtract the height of the current bar. Move `right` pointer to the left.
43+
6. Continue this process until the two pointers meet.
44+
7. Return the total amount of water trapped.
45+
46+
Here's the implementation:
47+
48+
```swift
49+
class Solution {
50+
func trap(_ height: [Int]) -> Int {
51+
var ans = 0
52+
var left = 0, right = height.count - 1
53+
var leftMax = 0, rightMax = 0
54+
while left < right {
55+
let leftHeight = height[left], rightHeight = height[right]
56+
if leftHeight < rightHeight {
57+
if leftHeight >= leftMax {
58+
leftMax = leftHeight
59+
} else {
60+
ans += leftMax - leftHeight
61+
}
62+
left += 1
63+
} else {
64+
if rightHeight >= rightMax {
65+
rightMax = rightHeight
66+
} else {
67+
ans += rightMax - rightHeight
68+
}
69+
right -= 1
70+
}
71+
}
72+
return ans
73+
}
74+
}
75+
```
76+
77+
This implementation provides a solution to the "Trapping Rain Water" problem in Swift. It calculates the amount of water that can be trapped between bars by using two pointers to track the left and right boundaries and two variables to track the maximum heights of bars encountered from the left and right directions.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
[![](https://img.shields.io/github/stars/LeetCode-in-Swift/LeetCode-in-Swift?label=Stars&style=flat-square)](https://github.com/LeetCode-in-Swift/LeetCode-in-Swift)
2+
[![](https://img.shields.io/github/forks/LeetCode-in-Swift/LeetCode-in-Swift?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/LeetCode-in-Swift/LeetCode-in-Swift/fork)
3+
4+
## 45\. Jump Game II
5+
6+
Medium
7+
8+
Given an array of non-negative integers `nums`, you are initially positioned at the first index of the array.
9+
10+
Each element in the array represents your maximum jump length at that position.
11+
12+
Your goal is to reach the last index in the minimum number of jumps.
13+
14+
You can assume that you can always reach the last index.
15+
16+
**Example 1:**
17+
18+
**Input:** nums = [2,3,1,1,4]
19+
20+
**Output:** 2
21+
22+
**Explanation:** The minimum number of jumps to reach the last index is 2. Jump 1 step from index 0 to 1, then 3 steps to the last index.
23+
24+
**Example 2:**
25+
26+
**Input:** nums = [2,3,0,1,4]
27+
28+
**Output:** 2
29+
30+
**Constraints:**
31+
32+
* <code>1 <= nums.length <= 10<sup>4</sup></code>
33+
* `0 <= nums[i] <= 1000`
34+
35+
To solve the "Jump Game II" problem in Swift with a `Solution` class, we can follow these steps:
36+
37+
1. Define a `Solution` class.
38+
2. Define a method named `jump` that takes an array of non-negative integers `nums` as input and returns the minimum number of jumps required to reach the last index.
39+
3. Initialize variables `maxReach`, `steps`, and `end` to keep track of the maximum reachable position, the number of steps taken, and the end position respectively. Initialize `maxReach` to 0 and `end` to 0.
40+
4. Iterate through the array from index 0 to `nums.length - 2`:
41+
- Update `maxReach` as the maximum of `maxReach` and `i + nums[i]`.
42+
- If the current index `i` equals `end`, update `end` to `maxReach` and increment `steps`.
43+
5. Return `steps`.
44+
45+
Here's the implementation:
46+
47+
```swift
48+
public class Solution {
49+
public func jump(_ nums: [Int]) -> Int {
50+
var length = 0
51+
var maxLength = 0
52+
var minJump = 0
53+
54+
for i in 0..<nums.count - 1 {
55+
length -= 1
56+
maxLength -= 1
57+
maxLength = max(maxLength, nums[i])
58+
if length <= 0 {
59+
length = maxLength
60+
minJump += 1
61+
}
62+
if length >= nums.count - i - 1 {
63+
return minJump
64+
}
65+
}
66+
return minJump
67+
}
68+
}
69+
```
70+
71+
This implementation provides a solution to the "Jump Game II" problem in Swift. It calculates the minimum number of jumps required to reach the last index by iterating through the array and updating the maximum reachable position and the end position accordingly.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
[![](https://img.shields.io/github/stars/LeetCode-in-Swift/LeetCode-in-Swift?label=Stars&style=flat-square)](https://github.com/LeetCode-in-Swift/LeetCode-in-Swift)
2+
[![](https://img.shields.io/github/forks/LeetCode-in-Swift/LeetCode-in-Swift?label=Fork%20me%20on%20GitHub%20&style=flat-square)](https://github.com/LeetCode-in-Swift/LeetCode-in-Swift/fork)
3+
4+
## 46\. Permutations
5+
6+
Medium
7+
8+
Given an array `nums` of distinct integers, return _all the possible permutations_. You can return the answer in **any order**.
9+
10+
**Example 1:**
11+
12+
**Input:** nums = [1,2,3]
13+
14+
**Output:** [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
15+
16+
**Example 2:**
17+
18+
**Input:** nums = [0,1]
19+
20+
**Output:** [[0,1],[1,0]]
21+
22+
**Example 3:**
23+
24+
**Input:** nums = [1]
25+
26+
**Output:** [[1]]
27+
28+
**Constraints:**
29+
30+
* `1 <= nums.length <= 6`
31+
* `-10 <= nums[i] <= 10`
32+
* All the integers of `nums` are **unique**.
33+
34+
To solve the "Permutations" problem in Swift with a `Solution` class, we can follow these steps:
35+
36+
1. Define a `Solution` class.
37+
2. Define a method named `permute` that takes an array of distinct integers `nums` as input and returns a list of all possible permutations.
38+
3. Create an empty list to store the result permutations.
39+
4. Call a recursive helper function named `permuteHelper` to generate permutations.
40+
5. Inside the `permuteHelper` function:
41+
- If the current permutation size equals the length of the input array `nums`, add a copy of the current permutation to the result list.
42+
- Otherwise, iterate through each element of `nums`:
43+
- If the current element is not already in the permutation, add it to the current permutation, and recursively call `permuteHelper` with the updated permutation and the remaining elements of `nums`.
44+
- After the recursive call, remove the last element from the permutation to backtrack.
45+
6. Return the result list.
46+
47+
Here's the implementation:
48+
49+
```swift
50+
public class Solution {
51+
public func permute(_ nums: [Int]) -> [[Int]] {
52+
if nums.isEmpty {
53+
return []
54+
}
55+
var finalResult = \[\[Int]]()
56+
var currResult = [Int]()
57+
var used = [Bool](repeating: false, count: nums.count)
58+
permuteRecur(nums, &finalResult, &currResult, &used)
59+
return finalResult
60+
}
61+
62+
private func permuteRecur(_ nums: [Int], _ finalResult: inout [[Int]], _ currResult: inout [Int], _ used: inout [Bool]) {
63+
if currResult.count == nums.count {
64+
finalResult.append(currResult)
65+
return
66+
}
67+
for i in 0..<nums.count {
68+
if used[i] {
69+
continue
70+
}
71+
currResult.append(nums[i])
72+
used[i] = true
73+
permuteRecur(nums, &finalResult, &currResult, &used)
74+
used[i] = false
75+
currResult.removeLast()
76+
}
77+
}
78+
}
79+
```
80+
81+
This implementation provides a solution to the "Permutations" problem in Swift. It generates all possible permutations of the given array of distinct integers using backtracking.

0 commit comments

Comments
 (0)