feat: add solutions to lc problem: No.0922 (#4019)

No.0922.Sort Array By Parity II
This commit is contained in:
Libin YANG 2025-02-04 08:53:50 +08:00 committed by GitHub
parent bbf6fec58e
commit b13b1d1464
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 61 additions and 6 deletions

View File

@ -64,11 +64,11 @@ tags:
### 方法一:双指针
我们用两个指针 $i$ 和 $j$ 分别指向偶数下标和奇数下标。
我们用两个指针 $i$ 和 $j$ 分别指向偶数下标和奇数下标,初始时 $i = 0$, $j = 1$
当 $i$ 指向偶数下标时,如果 $nums[i]$ 是奇数,那么我们需要找到一个奇数下标 $j$,使得 $nums[j]$ 是偶数,然后交换 $nums[i]$ 和 $nums[j]$。继续遍历,直到 $i$ 指向数组末尾。
当 $i$ 指向偶数下标时,如果 $\textit{nums}[i]$ 是奇数,那么我们需要找到一个奇数下标 $j$,使得 $\textit{nums}[j]$ 是偶数,然后交换 $\textit{nums}[i]$ 和 $\textit{nums}[j]$。继续遍历,直到 $i$ 指向数组末尾。
时间复杂度 $O(n)$,其中 $n$ 是数组的长度。空间复杂度 $O(1)$。
时间复杂度 $O(n)$,其中 $n$ 是数组 $\textit{nums}[i]$ 的长度。空间复杂度 $O(1)$。
<!-- tabs:start -->
@ -157,6 +157,26 @@ function sortArrayByParityII(nums: number[]): number[] {
}
```
#### Rust
```rust
impl Solution {
pub fn sort_array_by_parity_ii(mut nums: Vec<i32>) -> Vec<i32> {
let n = nums.len();
let mut j = 1;
for i in (0..n).step_by(2) {
if nums[i] % 2 != 0 {
while nums[j] % 2 != 0 {
j += 2;
}
nums.swap(i, j);
}
}
nums
}
}
```
#### JavaScript
```js

View File

@ -61,11 +61,11 @@ tags:
### Solution 1: Two Pointers
We use two pointers $i$ and $j$ to point to even and odd indices respectively.
We use two pointers $i$ and $j$ to point to even and odd indices, respectively. Initially, $i = 0$ and $j = 1$.
When $i$ points to an even index, if $nums[i]$ is odd, then we need to find an odd index $j$ such that $nums[j]$ is even, and then swap $nums[i]$ and $nums[j]$. Continue to iterate until $i$ points to the end of the array.
When $i$ points to an even index, if $\textit{nums}[i]$ is odd, we need to find an odd index $j$ such that $\textit{nums}[j]$ is even, and then swap $\textit{nums}[i]$ and $\textit{nums}[j]$. Continue traversing until $i$ reaches the end of the array.
The time complexity is $O(n)$, where $n$ is the length of the array. The space complexity is $O(1)$.
The time complexity is $O(n)$, where $n$ is the length of the array $\textit{nums}$. The space complexity is $O(1)$.
<!-- tabs:start -->
@ -154,6 +154,26 @@ function sortArrayByParityII(nums: number[]): number[] {
}
```
#### Rust
```rust
impl Solution {
pub fn sort_array_by_parity_ii(mut nums: Vec<i32>) -> Vec<i32> {
let n = nums.len();
let mut j = 1;
for i in (0..n).step_by(2) {
if nums[i] % 2 != 0 {
while nums[j] % 2 != 0 {
j += 2;
}
nums.swap(i, j);
}
}
nums
}
}
```
#### JavaScript
```js

View File

@ -0,0 +1,15 @@
impl Solution {
pub fn sort_array_by_parity_ii(mut nums: Vec<i32>) -> Vec<i32> {
let n = nums.len();
let mut j = 1;
for i in (0..n).step_by(2) {
if nums[i] % 2 != 0 {
while nums[j] % 2 != 0 {
j += 2;
}
nums.swap(i, j);
}
}
nums
}
}