|
33 | 33 | <pre>
|
34 | 34 | <strong>Input:</strong> nums1 = [1,3,5,4], nums2 = [1,2,3,7]
|
35 | 35 | <strong>Output:</strong> 1
|
36 |
| -<strong>Explanation:</strong> |
| 36 | +<strong>Explanation:</strong> |
37 | 37 | Swap nums1[3] and nums2[3]. Then the sequences are:
|
38 | 38 | nums1 = [1, 3, 5, 7] and nums2 = [1, 2, 3, 4]
|
39 | 39 | which are both strictly increasing.
|
@@ -61,7 +61,21 @@ which are both strictly increasing.
|
61 | 61 |
|
62 | 62 | <!-- solution:start -->
|
63 | 63 |
|
64 |
| -### Solution 1 |
| 64 | +### Solution 1: Dynamic Programming |
| 65 | + |
| 66 | +Define $a$ and $b$ to represent the minimum number of swaps needed to make the element sequences strictly increasing up to index $[0..i]$, with the $i$-th element not swapped and swapped, respectively. The index starts from $0$. |
| 67 | + |
| 68 | +When $i=0$, we have $a = 0$ and $b = 1$. |
| 69 | + |
| 70 | +When $i \gt 0$, we first save the previous values of $a$ and $b$ in $x$ and $y$, and then discuss the following cases: |
| 71 | + |
| 72 | +If $nums1[i - 1] \ge nums1[i]$ or $nums2[i - 1] \ge nums2[i]$, to make both sequences strictly increasing, the relative positions of the elements at indices $i-1$ and $i$ must change. That is, if the previous position was swapped, then the current position should not be swapped, so $a = y$; if the previous position was not swapped, then the current position must be swapped, so $b = x + 1$. |
| 73 | + |
| 74 | +Otherwise, the relative positions of the elements at indices $i-1$ and $i$ do not need to change, so $b = y + 1$. Additionally, if $nums1[i - 1] \lt nums2[i]$ and $nums2[i - 1] \lt nums1[i]$, the relative positions of the elements at indices $i-1$ and $i$ can change, so $a$ and $b$ can take the smaller values, thus $a = \min(a, y)$ and $b = \min(b, x + 1)$. |
| 75 | + |
| 76 | +Finally, return the smaller value between $a$ and $b$. |
| 77 | + |
| 78 | +The time complexity is $O(n)$, and the space complexity is $O(1)$. |
65 | 79 |
|
66 | 80 | <!-- tabs:start -->
|
67 | 81 |
|
@@ -151,6 +165,29 @@ func minSwap(nums1 []int, nums2 []int) int {
|
151 | 165 | }
|
152 | 166 | ```
|
153 | 167 |
|
| 168 | +#### TypeScript |
| 169 | + |
| 170 | +```ts |
| 171 | +function minSwap(nums1: number[], nums2: number[]): number { |
| 172 | + let [a, b] = [0, 1]; |
| 173 | + for (let i = 1; i < nums1.length; ++i) { |
| 174 | + let x = a, |
| 175 | + y = b; |
| 176 | + if (nums1[i - 1] >= nums1[i] || nums2[i - 1] >= nums2[i]) { |
| 177 | + a = y; |
| 178 | + b = x + 1; |
| 179 | + } else { |
| 180 | + b = y + 1; |
| 181 | + if (nums1[i - 1] < nums2[i] && nums2[i - 1] < nums1[i]) { |
| 182 | + a = Math.min(a, y); |
| 183 | + b = Math.min(b, x + 1); |
| 184 | + } |
| 185 | + } |
| 186 | + } |
| 187 | + return Math.min(a, b); |
| 188 | +} |
| 189 | +``` |
| 190 | + |
154 | 191 | <!-- tabs:end -->
|
155 | 192 |
|
156 | 193 | <!-- solution:end -->
|
|
0 commit comments