From 224dc5f5612fb916bb6e97fd1026d2bc2c49bd30 Mon Sep 17 00:00:00 2001 From: jerryfishcode <91447694+jerryfishcode@users.noreply.github.com> Date: Mon, 27 Sep 2021 18:54:45 +0800 Subject: [PATCH] =?UTF-8?q?Update=200922.=E6=8C=89=E5=A5=87=E5=81=B6?= =?UTF-8?q?=E6=8E=92=E5=BA=8F=E6=95=B0=E7=BB=84II.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0922.按奇偶排序数组II.md | 51 ++++++++++++++++++++++++ 1 file changed, 51 insertions(+) diff --git a/problems/0922.按奇偶排序数组II.md b/problems/0922.按奇偶排序数组II.md index 5b66247e..05cff32a 100644 --- a/problems/0922.按奇偶排序数组II.md +++ b/problems/0922.按奇偶排序数组II.md @@ -209,6 +209,57 @@ func sortArrayByParityII(nums []int) []int { ## JavaScript ```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; +}; ``` -----------------------