[Easy] - 283. Move Zeroes (C++)
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
아니 방금 Two-pointer technique 을 봐놓고, 혼자 엉뚱하게 풀다가 시간만 낭비했네요. 바로 저번 글에 Two-pointer technique 을 언급 했는데 예제가 없으면 아쉬워서, (+ 낭비한 시간이 아까워서) 어렵지 않지만 작성해봅니다. 우선은 문제를 풀고 습관을 들이는게 중요하기도 하고... / LeetCode 내부에 있는 커리큘럼을 따라 예제를 풀어서 그런지 난이도 Easy문제를 많이 풀게 되네요!
문제의 조건 중 핵심 사항들을 정리하면 아래와 같습니다.
▶ 입력된 배열에서 0을 지운다 (or 배열의 뒤로 보낸다.)
▶ 0이 아닌 숫자들의 순서는 유지한다.
▶ Example )
Input: nums = [0,1,0,3,12]
Output: [1,3,12,0,0]
이번 문제는 Two-pointer technique의 WritePointer와 ReadPointer를 활용하여 해결해 보았습니다. WritePointer의 역할은 0이 아닐 경우, 앞에서 부터 숫자를 작성해가는 말그대로 WritePointer 역할로 활용하였고 ReadPointer는 배열의 원소들을 읽는 역할로 활용하여 작성하였습니다.
입력된 배열의 ReadPointer 번째 인덱스가 0이 아닐 경우, 0부터 시작되는 WritePointer번째 인덱스에 값을 넣어주며, 넣어준 후 WritePointer의 index를 1씩 증가시켜 주는 형태로 반복합니다. 배열의 사이즈 만큼 반복이 끝나면 앞에서 부터 0이 아닌 원소들로 순서대로 채워지게 됩니다.
class Solution {
public:
void moveZeroes(vector<int>& nums) {
int nReadPointer;
int nWritePointer = 0;
for(nReadPointer = 0; nReadPointer < nums.size(); nReadPointer++) {
if(nums[nReadPointer] != 0) {
nums[nWritePointer++] = nums[nReadPointer];
}
}
for(int i = nums.size()-1; i >= nWritePointer; i--) {
nums[i] = 0;
}
}
};
마지막엔 입력된 배열의 총사이즈에서 WirtePointer 갯수 만큼 빼주면, 배열안에 0의 갯수를 의미하므로 배열의 뒷자리에서 부터 0을 대입해주어 해결하였습니다.
내일 출근하기 싫어요.. 몇문제 더 풀어봐야 겠네요. 작성하고 보니 너무 간단한 문제인 것 같습니다! ㅋㅋ..