๋ฌธ์ |
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 <= A.length <= 5000
0 <= A[i] <= 5000
ํ์ด๊ณผ์ |
(1) ๊ท์น
์ค๋ฆ์ฐจ์,๋ด๋ฆผ์ฐจ์ ์๊ด์์ด ์ง์๋ฅผ ์ ๋ถ ์์ ๋ฐฐ์นํ๋๋ก ํฉ๋๋ค.
๋จ,
1 <= A.length <= 5000
0 <= A[i] <= 5000
์ด๋ผ๋ ์กฐ๊ฑด์ ๊ณ ๋ คํ์ฌ ์ต๋ํ ์ฐ์ฐํ์๊ฐ ์ ๋๋ก ๊ตฌํํฉ๋๋ค.
(2) ์์
swap()์ ์ด์ฉํ๊ฑฐ๋
์ง์๋ค๋ง ๋ค๋ฅธ ๋ฒํผ์ ๋ฃ์ํ, ํ์๋ง ๋จ์ ์๋ฐฐ์ด๊ณผ ํฉํด์ ์ถ๋ ฅํ๋ ๋ฐฉ๋ฒ์ ์ฌ์ฉํฉ๋๋ค.
๋๋ for๋ฌธ์ ๋๋ฉด์ ์ ๋ฒํผ์ ์ง์๋ ๋งจ์, ํ์๋ ๋งจ๋ค์๋ค๊ฐ ์ถ๊ฐํด์ค๋๋ค.
(3) ์ฝ๋
C++
#include <iostream> #include <vector> using namespace std; vector<int> sortArrayByParity(vector<int>& A) { vector<int> answer; for (vector<int>::iterator it = A.begin(); it != A.end(); ) { if (*it % 2 == 0)//์ง์ { answer.push_back(*it); it = A.erase(it); } else it++; } answer.insert(answer.end(), A.begin(), A.end()); return answer; } | cs |
Python
(1) ๋ฐํ์ ์๋ ์ ์ผ ๋น ๋ฆ
class Solution: def sortArrayByParity(self, A): odd=[] even=[] for i in range(len(A)): if A[i]%2==0: even.append(A[i]) else: odd.append(A[i]) return even+odd | cs |
(2)
class Solution: def sortArrayByParity(self, A): answer=[] for i in range(len(A)): if A[i]%2==0: answer.insert(0,A[i]) else: answer.append(A[i]) return answer | cs |
(3)
class Solution: def sortArrayByParity(self, A): answer = collections.deque() for i in range(len(A)): answer.appendleft(A[i]) if (A[i]%2==0) else answer.append(A[i]) return answer | cs |