Skip to content

Commit d6328a9

Browse files
committedJul 4, 2024
Added tasks 215-1143
1 parent 59595bf commit d6328a9

File tree

29 files changed

+2038
-53
lines changed

29 files changed

+2038
-53
lines changed
 

‎README.md

+128-53
Large diffs are not rendered by default.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,108 @@
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+
## 152\. Maximum Product Subarray
5+
6+
Medium
7+
8+
Given an integer array `nums`, find a contiguous non-empty subarray within the array that has the largest product, and return _the product_.
9+
10+
It is **guaranteed** that the answer will fit in a **32-bit** integer.
11+
12+
A **subarray** is a contiguous subsequence of the array.
13+
14+
**Example 1:**
15+
16+
**Input:** nums = [2,3,-2,4]
17+
18+
**Output:** 6
19+
20+
**Explanation:** [2,3] has the largest product 6.
21+
22+
**Example 2:**
23+
24+
**Input:** nums = [-2,0,-1]
25+
26+
**Output:** 0
27+
28+
**Explanation:** The result cannot be 2, because [-2,-1] is not a subarray.
29+
30+
**Constraints:**
31+
32+
* <code>1 <= nums.length <= 2 * 10<sup>4</sup></code>
33+
* `-10 <= nums[i] <= 10`
34+
* The product of any prefix or suffix of `nums` is **guaranteed** to fit in a **32-bit** integer.
35+
36+
To solve the "152. Maximum Product Subarray" problem in Swift using the provided `Solution` class:
37+
38+
### Steps to Solve the Problem
39+
40+
1. **Initialize Variables**:
41+
- Create a variable `left` to keep track of the product of elements from the left.
42+
- Create a variable `right` to keep track of the product of elements from the right.
43+
- Initialize a variable `res` to store the maximum product found so far.
44+
45+
2. **Iterate Through the Array**:
46+
- Use a loop to iterate through the array from the start to the end.
47+
- Simultaneously iterate through the array from the end to the start.
48+
49+
3. **Update Products**:
50+
- For each iteration, update the `left` product by multiplying it with the current element from the left side.
51+
- Update the `right` product by multiplying it with the current element from the right side.
52+
53+
4. **Handle Zeros**:
54+
- If the `left` product is zero, reset it to one to start a new subarray.
55+
- Similarly, if the `right` product is zero, reset it to one to start a new subarray.
56+
57+
5. **Update Maximum Product**:
58+
- Update the `res` with the maximum value between `res`, `left`, and `right`.
59+
60+
6. **Return Result**:
61+
- After completing the loop, return the maximum product found, converted to an integer.
62+
63+
### Swift Solution
64+
65+
```swift
66+
class Solution {
67+
func maxProduct(_ nums: [Int]) -> Int {
68+
var left: Double = 1
69+
var right: Double = 1
70+
var j = nums.count - 1
71+
var res: Double = Double(Int.min)
72+
73+
for i in 0..<nums.count {
74+
if left == 0 { left = 1 }
75+
if right == 0 { right = 1 }
76+
77+
left *= Double(nums[i])
78+
right *= Double(nums[j])
79+
80+
j -= 1
81+
82+
res = max(res, max(left, right))
83+
}
84+
85+
return Int(res)
86+
}
87+
}
88+
```
89+
90+
### Explanation of the Example Cases
91+
92+
- **Example 1**:
93+
- **Input**: `nums = [2,3,-2,4]`
94+
- The contiguous subarray `[2,3]` has the largest product `6`.
95+
- **Output**: `6`
96+
97+
- **Example 2**:
98+
- **Input**: `nums = [-2,0,-1]`
99+
- The maximum product subarray is `[0]` which has a product of `0`.
100+
- **Output**: `0`
101+
102+
### Constraints
103+
104+
- `1 <= nums.length <= 2 * 10^4`
105+
- `-10 <= nums[i] <= 10`
106+
- The product of any prefix or suffix of `nums` is guaranteed to fit in a 32-bit integer.
107+
108+
By following these steps and using the provided solution, you can solve the "152. Maximum Product Subarray" problem in Swift efficiently.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
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+
## 215\. Kth Largest Element in an Array
5+
6+
Medium
7+
8+
Given an integer array `nums` and an integer `k`, return _the_ <code>k<sup>th</sup></code> _largest element in the array_.
9+
10+
Note that it is the <code>k<sup>th</sup></code> largest element in the sorted order, not the <code>k<sup>th</sup></code> distinct element.
11+
12+
**Example 1:**
13+
14+
**Input:** nums = [3,2,1,5,6,4], k = 2
15+
16+
**Output:** 5
17+
18+
**Example 2:**
19+
20+
**Input:** nums = [3,2,3,1,2,4,5,5,6], k = 4
21+
22+
**Output:** 4
23+
24+
**Constraints:**
25+
26+
* <code>1 <= k <= nums.length <= 10<sup>4</sup></code>
27+
* <code>-10<sup>4</sup> <= nums[i] <= 10<sup>4</sup></code>
28+
29+
## Solution
30+
31+
```swift
32+
class Solution {
33+
func findKthLargest(_ nums: [Int], _ k: Int) -> Int {
34+
let sortedNums = nums.sorted()
35+
return sortedNums[sortedNums.count - k]
36+
}
37+
}
38+
```
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
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+
## 221\. Maximal Square
5+
6+
Medium
7+
8+
Given an `m x n` binary `matrix` filled with `0`'s and `1`'s, _find the largest square containing only_ `1`'s _and return its area_.
9+
10+
**Example 1:**
11+
12+
![](https://assets.leetcode.com/uploads/2020/11/26/max1grid.jpg)
13+
14+
**Input:** matrix = \[\["1","0","1","0","0"],["1","0","1","1","1"],["1","1","1","1","1"],["1","0","0","1","0"]]
15+
16+
**Output:** 4
17+
18+
**Example 2:**
19+
20+
![](https://assets.leetcode.com/uploads/2020/11/26/max2grid.jpg)
21+
22+
**Input:** matrix = \[\["0","1"],["1","0"]]
23+
24+
**Output:** 1
25+
26+
**Example 3:**
27+
28+
**Input:** matrix = \[\["0"]]
29+
30+
**Output:** 0
31+
32+
**Constraints:**
33+
34+
* `m == matrix.length`
35+
* `n == matrix[i].length`
36+
* `1 <= m, n <= 300`
37+
* `matrix[i][j]` is `'0'` or `'1'`.
38+
39+
## Solution
40+
41+
```swift
42+
class Solution {
43+
func maximalSquare(_ matrix: [[Character]]) -> Int {
44+
guard matrix.count > 0 && matrix[0].count > 0 else { return 0 }
45+
var square = Array(repeating: Array(repeating: 0, count: matrix[0].count), count: matrix.count)
46+
var curMaxLen = 0
47+
48+
for i in 0..<matrix.count {
49+
for j in 0..<matrix[0].count {
50+
// when first col or row, set value manually, avoid "-1" index as well
51+
if i == 0 || j == 0 {
52+
square[i][j] = Int(String(matrix[i][j]))!
53+
}
54+
else if matrix[i][j] == "1" {
55+
square[i][j] = min(min(square[i-1][j], square[i][j-1]), square[i-1][j-1]) + 1
56+
}
57+
curMaxLen = max(curMaxLen, square[i][j])
58+
}
59+
}
60+
return curMaxLen*curMaxLen
61+
}
62+
}
63+
```
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
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+
## 226\. Invert Binary Tree
5+
6+
Easy
7+
8+
Given the `root` of a binary tree, invert the tree, and return _its root_.
9+
10+
**Example 1:**
11+
12+
![](https://assets.leetcode.com/uploads/2021/03/14/invert1-tree.jpg)
13+
14+
**Input:** root = [4,2,7,1,3,6,9]
15+
16+
**Output:** [4,7,2,9,6,3,1]
17+
18+
**Example 2:**
19+
20+
![](https://assets.leetcode.com/uploads/2021/03/14/invert2-tree.jpg)
21+
22+
**Input:** root = [2,1,3]
23+
24+
**Output:** [2,3,1]
25+
26+
**Example 3:**
27+
28+
**Input:** root = []
29+
30+
**Output:** []
31+
32+
**Constraints:**
33+
34+
* The number of nodes in the tree is in the range `[0, 100]`.
35+
* `-100 <= Node.val <= 100`
36+
37+
## Solution
38+
39+
```swift
40+
/**
41+
* Definition for a binary tree node.
42+
* public class TreeNode {
43+
* public var val: Int
44+
* public var left: TreeNode?
45+
* public var right: TreeNode?
46+
* public init() { self.val = 0; self.left = nil; self.right = nil; }
47+
* public init(_ val: Int) { self.val = val; self.left = nil; self.right = nil; }
48+
* public init(_ val: Int, _ left: TreeNode?, _ right: TreeNode?) {
49+
* self.val = val
50+
* self.left = left
51+
* self.right = right
52+
* }
53+
* }
54+
*/
55+
class Solution {
56+
func invertTree(_ root: TreeNode?) -> TreeNode? {
57+
if root?.left != nil || root?.right != nil {
58+
let leftTree = root?.left
59+
let rightTree = root?.right
60+
61+
root?.left = rightTree
62+
root?.right = leftTree
63+
64+
invertTree(root?.left)
65+
invertTree(root?.right)
66+
}
67+
return root
68+
}
69+
}
70+
```
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
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+
## 230\. Kth Smallest Element in a BST
5+
6+
Medium
7+
8+
Given the `root` of a binary search tree, and an integer `k`, return _the_ <code>k<sup>th</sup></code> _smallest value (**1-indexed**) of all the values of the nodes in the tree_.
9+
10+
**Example 1:**
11+
12+
![](https://assets.leetcode.com/uploads/2021/01/28/kthtree1.jpg)
13+
14+
**Input:** root = [3,1,4,null,2], k = 1
15+
16+
**Output:** 1
17+
18+
**Example 2:**
19+
20+
![](https://assets.leetcode.com/uploads/2021/01/28/kthtree2.jpg)
21+
22+
**Input:** root = [5,3,6,2,4,null,null,1], k = 3
23+
24+
**Output:** 3
25+
26+
**Constraints:**
27+
28+
* The number of nodes in the tree is `n`.
29+
* <code>1 <= k <= n <= 10<sup>4</sup></code>
30+
* <code>0 <= Node.val <= 10<sup>4</sup></code>
31+
32+
**Follow up:** If the BST is modified often (i.e., we can do insert and delete operations) and you need to find the kth smallest frequently, how would you optimize?
33+
34+
## Solution
35+
36+
```swift
37+
/**
38+
* Definition for a binary tree node.
39+
* public class TreeNode {
40+
* public var val: Int
41+
* public var left: TreeNode?
42+
* public var right: TreeNode?
43+
* public init() { self.val = 0; self.left = nil; self.right = nil; }
44+
* public init(_ val: Int) { self.val = val; self.left = nil; self.right = nil; }
45+
* public init(_ val: Int, _ left: TreeNode?, _ right: TreeNode?) {
46+
* self.val = val
47+
* self.left = left
48+
* self.right = right
49+
* }
50+
* }
51+
*/
52+
class Solution {
53+
func kthSmallest(_ root: TreeNode?, _ k: Int) -> Int {
54+
var vals = [Int]()
55+
var minVal = Int.max
56+
var maxVal = Int.min
57+
traverse(root, &vals, &minVal, &maxVal)
58+
var countingArray = Array(repeating: -1, count: maxVal - minVal + 1)
59+
for val in vals { countingArray[val - minVal] = val }
60+
var i = 0
61+
for val in countingArray {
62+
guard val != -1 else { continue }
63+
i += 1
64+
if i == k { return val }
65+
}
66+
return -1
67+
}
68+
69+
private func traverse(
70+
_ node: TreeNode?,
71+
_ arr: inout [Int],
72+
_ minVal: inout Int,
73+
_ maxVal: inout Int
74+
) {
75+
guard let node else { return }
76+
minVal = min(minVal, node.val)
77+
maxVal = max(maxVal, node.val)
78+
arr.append(node.val)
79+
traverse(node.left, &arr, &minVal, &maxVal)
80+
traverse(node.right, &arr, &minVal, &maxVal)
81+
}
82+
}
83+
```

0 commit comments

Comments
 (0)