본문 바로가기
알고리즘 문제풀이/leetcode

[leetcode 283] Move Zeroes

by m2162003 2020. 10. 12.

Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements.

Example:

Input: [0,1,0,3,12] Output: [1,3,12,0,0]

 

문제: 0을 전부 뒤로 미루는 문제

 

풀이 :

0이 아닌 숫자를 앞에서 부터 채우고 나머지 배열에 0을 채운다.

class Solution {
public:
    void moveZeroes(vector<int>& nums) {
       
        int last = 0;
        //0이 아닌 숫자를 앞으로 밀어넣기
        for(int i=0; i<nums.size(); i++){
           if(nums[i] != 0){
               nums[last++] = nums[i];
           }
        }
        
        //나머지는 0으로 채운다.
        for(; last<nums.size(); last++){
            nums[last] = 0;
        }
    }
};

댓글