leetcode 922. Sort Array By Parity II

Given an array A of non-negative integers, half of the integers in A are odd, and half of the integers are even.

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

You may return any answer array that satisfies this condition.

 

Example 1:

Input: [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.

 

Note:

  1. 2 <= A.length <= 20000
  2. A.length % 2 == 0
  3. 0 <= A[i] <= 1000

 

题目大意:给定一个数组,一半奇数,一半偶数,要求返回的数组:奇数在奇数位,偶数在偶数位。

思路一:开辟一个同样大小的数组,遍历一遍原数组,奇数放在新开辟数组的奇数位,偶数放在新开辟数组的偶数位。

 1 class Solution {
 2 public:
 3     vector<int> sortArrayByParityII(vector<int>& A) {
 4         int len = A.size();
 5         vector<int> res(len, 0);
 6         int even = 1, odd = 0;
 7         for (int i = 0; i < len; ++i) {
 8             if (1 == (A[i] & 1))  {
 9                 res[even] = A[i];
10                 even += 2;
11             } else {
12                 res[odd] = A[i];
13                 odd += 2;
14             }
15         }
16         return res;
17     }
18 };

时间复杂度:O(N), 空间复杂度:O(N)。

 

思路二:不新开辟空间,交换偶数位的第一个奇数和奇数位的第一个偶数。

 1 vector<int> sortArrayByParityII(vector<int>& A) {
 2         int len = A.size();
 3         int even = 1;
 4         for (int i = 0; i < len; i += 2) {
 5             if (1 == (A[i] & 1))  { //偶数位的奇数
 6                 while ((A[even] & 1) == 1) even += 2; //如果当前奇数位是奇数,则向后面找,直到找到第一个奇数位的偶数。
 7                 swap(A[i], A[even]);
 8             } 
 9         }
10         return A;
11     }

时间复杂度:O(N), 空间复杂度: O(1)

 

你可能感兴趣的:(leetcode 922. Sort Array By Parity II)