본문 바로가기

Algorithm/Implementation

(C++) - LeetCode (easy) 1089. Duplicate Zeros

반응형

https://leetcode.com/problems/duplicate-zeros/

 

Duplicate Zeros - LeetCode

Can you solve this real interview question? Duplicate Zeros - Given a fixed-length integer array arr, duplicate each occurrence of zero, shifting the remaining elements to the right. Note that elements beyond the length of the original array are not writte

leetcode.com

간단 구현 문제였습니다.

📕 풀이방법

📔 풀이과정

정답 vector 변수 ans와 0을 복사해 넣을 vector를 각각 선언해줍니다.1. arr의 원소를 순회하며 원소가 0이 아니면 그 원소를 v에 넣어주고 0이라면 v에 0을 한번 더 넣어줍니다.2. v는 size가 arr보다 많으므로 arr size만큼의 원소를 왼쪽부터 ans에 넣어줍니다.3. arr에 ans를 복사해 저장해줍니다.


📕 Code

📔 C++

class Solution {
public:
    void duplicateZeros(vector<int>& arr) {
        vector <int> ans;
        vector <int> v;
        for(auto a : arr) {
            if(a) v.push_back(a);
            else v.push_back(0),v.push_back(0);
        }
        for(int i = 0; i < arr.size(); i++) {
            ans.push_back(v[i]);
        }
        arr = ans;
    }
};

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