905. Sort Array By Parity

【题目】

Given an array A of non-negative integers, return an array consisting of all the even elements of A, followed by all the odd elements of A.

You may return any answer array that satisfies this condition.

 

Example 1:

Input: [3,1,2,4]
Output: [2,4,3,1]
The outputs [4,2,3,1], [2,4,1,3], and [4,2,1,3] would also be accepted.

 

Note:

  1. 1 <= A.length <= 5000
  2. 0 <= A[i] <= 5000
 

【题意】

将数组中的偶数元素放在数组的前一部分,奇数元素在后一部分。

【解答】

两个指针,将奇数元素和后部分的偶数元素替换。

时间 O(N) 空间 O(1)

【代码】

 1 class Solution {
 2 public:
 3     vector<int> sortArrayByParity(vector<int>& A) {
 4         int len = A.size();
 5         int i = 0, j = len - 1;
 6         while(i < j){
 7             if(A[i] % 2 == 0){
 8                 i ++;
 9                 continue;
10             }
11             if(A[j] % 2 != 0){
12                 j --;
13                 continue;
14             }
15             int temp = A[i];
16             A[i] = A[j];
17             A[j] = temp;
18         }
19         return A;
20     }
21 };

 

posted @ 2019-01-23 17:47  xxxinn  阅读(146)  评论(0)    收藏  举报