[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。

给定一个非负整数数组 nums,  nums 中一半整数是 奇数 ,一半整数是 偶数 。

对数组进行排序,以便当 nums[i] 为奇数时,i 也是 奇数 ;当 nums[i] 为偶数时, i 也是 偶数 。

你可以返回 任何满足上述条件的数组作为答案 。

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/sort-array-by-parity-ii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

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

时间O(n)

空间O(1)

Java实现

 1 class Solution {
 2     public int[] sortArrayByParityII(int[] nums) {
 3         int i = 0;
 4         int j = 1;
 5         int n = nums.length;
 6         while (i < n && j < n) {
 7             while (i < n && nums[i] % 2 == 0) {
 8                 i += 2;
 9             }
10             while (j < n && nums[j] % 2 == 1) {
11                 j += 2;
12             }
13             if (i < n && j < n) {
14                 swap(nums, i, j);
15             }
16         }
17         return nums;
18     }
19     
20     private void swap(int[] nums, int i, int j) {
21         int temp = nums[i];
22         nums[i] = nums[j];
23         nums[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 题目总结

posted @ 2020-11-12 02:59  CNoodle  阅读(114)  评论(0编辑  收藏  举报