본문 바로가기

Algorithm/자료구조

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

반응형

https://leetcode.com/problems/sort-array-by-parity/description/

 

Sort Array By Parity - LeetCode

Can you solve this real interview question? Sort Array By Parity - Given an integer array nums, move all the even integers at the beginning of the array followed by all the odd integers. Return any array that satisfies this condition.   Example 1: Input:

leetcode.com

자료구조를 사용해보는 문제였습니다.

📕 풀이방법

📔 입력 및 초기화

정답 vector ans를 선언해줍니다.

📔 풀이과정

nums의 원소를 순회하며 짝수인 부분을 먼저 넣고 다시 순회하며 홀수인 원소를 ans에 push합니다.

📔 정답 출력 | 반환

ans를 반환합니다.


📕 Code

📔 C++

class Solution {
public:
    vector<int> sortArrayByParity(vector<int>& nums) {
        vector <int> ans;
        for(auto n : nums) {
            if(n % 2 == 0) ans.push_back(n);
        }
        for(auto n : nums) {
            if(n % 2) ans.push_back(n);
        }
        return ans;
    }
};

📔 Rust

impl Solution {
    pub fn sort_array_by_parity(nums: Vec<i32>) -> Vec<i32> {
        let mut ans: Vec<i32> = Vec::new();
        for n in &nums {
            if n % 2 == 0 {
                ans.push(*n);
            }
        }
        for n in &nums {
            if n % 2 > 0 {
                ans.push(*n);
            }
        }
        return ans;
    }
}

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