[LeetCode] 922. Sort Array By Parity II

Given an array of integers nums, half of the integers in nums are odd, and the other half are even.

Sort the array so that whenever nums[i] is odd, i is odd, and whenever nums[i] is even, i is even.

Return any answer array that satisfies this condition.

Example 1:

Input: nums = [4,2,5,7]
Output: [4,5,2,7]
Explanation: [4,7,2,5], [2,5,4,7], [2,7,4,5] would also have been accepted.

Example 2:

Input: nums = [2,3]
Output: [2,3]

Constraints:

  • 2 <= nums.length <= 2 * 104
  • nums.length is even.
  • Half of the integers in nums are even.
  • 0 <= nums[i] <= 1000

Follow Up: Could you solve it in-place?

按奇偶排序数组 II。

题目即是题意。这道题跟版本一差不多,也是对数组进行有条件的排序和整理。这道题的思路是追击型的双指针,两个指针分别判断奇数下标和偶数下标上的数字是不是符合条件,用 while 循环控制。当两个指针都遇到各自不符合的 index 的时候,就停下然后互相 swap。

时间O(n)

空间O(1)

Java实现

 1 class Solution {
 2     public int[] sortArrayByParityII(int[] A) {
 3         int i = 0;
 4         int j = 1;
 5         int n = A.length;
 6         while (i < n && j < n) {
 7             while (i < n && A[i] % 2 == 0) {
 8                 i += 2;
 9             }
10             while (j < n && A[j] % 2 == 1) {
11                 j += 2;
12             }
13             if (i < n && j < n) {
14                 swap(A, i, j);
15             }
16         }
17         return A;
18     }
19 
20     private void swap(int[] A, int i, int j) {
21         int temp = A[i];
22         A[i] = A[j];
23         A[j] = temp;
24     }
25 }

JavaScript实现

 1 /**
 2  * @param {number[]} nums
 3  * @return {number[]}
 4  */
 5 var sortArrayByParityII = function(nums) {
 6     let i = 0;
 7     let j = 1;
 8     let n = nums.length;
 9     while (i < n && j < n) {
10         while (i < n && nums[i] % 2 == 0) {
11             i += 2;
12         }
13         while (j < n && nums[j] % 2 == 1) {
14             j += 2;
15         }
16         if (i < n && j < n) {
17             swap(nums, i, j);
18         }
19     }
20     return nums;
21 };
22 
23 var swap = function(nums, i, j) {
24     let temp = nums[i];
25     nums[i] = nums[j];
26     nums[j] = temp;
27 }

相关题目

75. Sort Colors

905. Sort Array By Parity

922. Sort Array By Parity II

LeetCode 题目总结

原文地址:https://www.cnblogs.com/cnoodle/p/13961936.html