본문 바로가기

Algorithm/Implementation

(C++, Rust) - LeetCode (easy) 922. Sort Array By Parity II

반응형

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
    }
}

*더 나은 내용을 위한 지적, 조언은 언제나 환영합니다.