본문 바로가기

Algorithm/Implementation

(C++) - LeetCode (easy) 283. Move Zeroes

반응형

https://leetcode.com/problems/move-zeroes/description/

 

Move Zeroes - LeetCode

Move Zeroes - Given an integer array nums, move all 0's to the end of it while maintaining the relative order of the non-zero elements. Note that you must do this in-place without making a copy of the array.   Example 1: Input: nums = [0,1,0,3,12] Output:

leetcode.com

구현 문제였습니다.

📕 풀이방법

📔 입력 및 초기화

0인 마지막 index를 저장할 변수 zeroIdx를 선언해줍니다.

📔 풀이과정

nums의 모든 원소를 순회합니다.

1. nums[i]가 0이 아니라면 마지막 0이었던 자리를 현재수로 채워줍니다.

연속으로 0이 아닌수가 이어지면 zeroIdx도 함께 증가하므로 zeroIdx는 항상 왼쪽부터 시작해서 0이 처음 나오는 index를 값으로 가지게 됩니다. 

2. 0이 아닌 수로 채워진 후 zeroIdx부터 nums.size() - 1까지 0으로 만들어줍니다.


📕 Code

📔 C++

class Solution {
public:
    void moveZeroes(vector<int>& nums) {
        int nonZeroIdx = 0;
        for(int i = 0; i < nums.size(); i++) {
            if(nums[i] != 0) {
                nums[nonZeroIdx++] = nums[i];
            }
        }
        for(int i = nonZeroIdx; i < nums.size(); i++) {
            nums[i] = 0;
        }
    }
};

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