mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 00:43:04 +08:00
Update 0922.按奇偶排序数组II.md
This commit is contained in:
@ -209,6 +209,57 @@ func sortArrayByParityII(nums []int) []int {
|
|||||||
## JavaScript
|
## JavaScript
|
||||||
|
|
||||||
```js
|
```js
|
||||||
|
//方法一
|
||||||
|
var sortArrayByParityII = function(nums) {
|
||||||
|
const n = nums.length;
|
||||||
|
// 分别存放 nums 中的奇数、偶数
|
||||||
|
let evenIndex = 0, oddIndex = 0;
|
||||||
|
// 初始化就确定数组大小,节省开销
|
||||||
|
const even = new Array(Math.floor(n/2));
|
||||||
|
const odd = new Array(Math.floor(n/2));
|
||||||
|
// 把A数组放进偶数数组,和奇数数组
|
||||||
|
for(let i = 0; i < n; i++){
|
||||||
|
if(nums[i] % 2 === 0) even[evenIndex++] = nums[i];
|
||||||
|
else odd[oddIndex++] = nums[i];
|
||||||
|
}
|
||||||
|
// 把奇偶数组重新存回 nums
|
||||||
|
let index = 0;
|
||||||
|
for(let i = 0; i < even.length; i++){
|
||||||
|
nums[index++] = even[i];
|
||||||
|
nums[index++] = odd[i];
|
||||||
|
}
|
||||||
|
return nums;
|
||||||
|
};
|
||||||
|
|
||||||
|
//方法二
|
||||||
|
var sortArrayByParityII = function(nums) {
|
||||||
|
const n = nums.length;
|
||||||
|
const result = new Array(n);
|
||||||
|
// 偶数下标 和 奇数下标
|
||||||
|
let evenIndex = 0, oddIndex = 1;
|
||||||
|
for(let i = 0; i < n; i++){
|
||||||
|
if(nums[i] % 2 === 0) {
|
||||||
|
result[evenIndex] = nums[i];
|
||||||
|
evenIndex += 2;
|
||||||
|
} else {
|
||||||
|
result[oddIndex] = nums[i];
|
||||||
|
oddIndex += 2;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
};
|
||||||
|
|
||||||
|
//方法三
|
||||||
|
var sortArrayByParityII = function(nums) {
|
||||||
|
let oddIndex = 1;
|
||||||
|
for(let i = 0; i < nums.length; i += 2){
|
||||||
|
if(nums[i] % 2 === 1){ // 在偶数位遇到了奇数
|
||||||
|
while(nums[oddIndex] % 2 !== 0) oddIndex += 2;// 在奇数位找一个偶数
|
||||||
|
[nums[oddIndex], nums[i]] = [nums[i], nums[oddIndex]]; // 解构赋值交换
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nums;
|
||||||
|
};
|
||||||
```
|
```
|
||||||
|
|
||||||
-----------------------
|
-----------------------
|
||||||
|
Reference in New Issue
Block a user