반응형
https://leetcode.com/problems/sort-array-by-parity-ii/description/
Sort Array By Parity II - LeetCode
Can you solve this real interview question? 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
leetcode.com
구현 문제였습니다.
📕 풀이방법
📔 입력 및 초기화
1. 정답 변수 ans와 짝수와 홀수 원소를 담을 변수 odd, even을 각각 선언해 줍니다.2. odd와 even에 nums만큼 원소를 순회해서 정보를 저장합니다.
📔 풀이과정
짝수번째 index에는 짝수값이, 홀수번째 index에는 홀수값이 들어가면 됩니다. 따라서 even, odd 원소 순으로 ans에 넣어준 뒤 각자의 값을 pop해줍니다.
📔 정답 출력 | 반환
ans를 반환합니다.
📕 Code
📔 C++
class Solution {
public:
vector<int> sortArrayByParityII(vector<int>& nums) {
vector <int> ans;
stack <int> odd, even;
for(auto n : nums) {
if(n%2) odd.push(n);
else even.push(n);
}
for(int i = 0; i < nums.size() / 2; i++) {
ans.push_back(even.top());
even.pop();
ans.push_back(odd.top());
odd.pop();
}
return ans;
}
};
📔 Rust
impl Solution {
pub fn sort_array_by_parity_ii(nums: Vec<i32>) -> Vec<i32> {
let mut ans: Vec<i32> = Vec::new();
let mut odd = Vec::new();
let mut even = Vec::new();
for n in nums {
if n % 2 == 1 {
odd.push(n);
} else {
even.push(n);
}
}
while !odd.is_empty() || !even.is_empty() {
if let Some(e) = even.pop() {
ans.push(e);
}
if let Some(o) = odd.pop() {
ans.push(o);
}
}
ans
}
}
*더 나은 내용을 위한 지적, 조언은 언제나 환영합니다.
'Algorithm > Implementation' 카테고리의 다른 글
(C++) - LeetCode (easy) 941. Valid Mountain Array (0) | 2023.09.08 |
---|---|
(C++, Rust) - LeetCode (easy) 925. Long Pressed Name (0) | 2023.09.04 |
(C++, Rust) - LeetCode (easy) 908. Smallest Range I (0) | 2023.08.28 |
(C++, Rust) - LeetCode (easy) 896. Monotonic Array (0) | 2023.08.22 |
(C++, Rust) - LeetCode (easy) 892. Surface Area of 3D Shapes (0) | 2023.08.18 |