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.
정수 배열 번호가 주어지면 0이 아닌 요소의 상대적인 순서를 유지하면서 0을 모두 그 끝으로 이동합니다.
이 작업은 어레이의 복사본을 만들지 않고 인 플레이스에서 수행해야 합니다.
Example 1:예제
Input: nums = [0,1,0,3,12]
Output: [1,3,12,0,0]
Example 2: 예제
Input: nums = [0]
Output: [0]
Constraints:제약조건
- 1 <= nums.length <= 104
- -2의31승 <= nums[i] <= 2의31승 - 1
class Solution {
public:
void moveZeroes(vector<int>& nums) {
int nIdx = 0;
for(int idx = 0; idx<nums.size(); idx++){
if(nums[idx]!= 0){
swap(nums[nIdx],nums[idx]);
nIdx++;
}
}
}
};
약간의 설명이 필요한 문제라 생각한다.
nIdx를 0 번째로 만들고 idx를 0부터 하나씩 증가시킨다.
Input: nums = [0,1,0,3,12]
예제를 확인해 보자
0일 경우 if문을 통과하지 못해 다시 for문으로 돌아가 idx + 1 해준다.
그럼 nums [1] 번째인 1과 만나게 된다.
그럼 if문의 조건을 통과하게 되고 nums [0] 번과 nums [1] 번이 교체가 이루어진다.
그럼 그 뒤 nums [0] 에는 1이 들어가고 nums [1] 번 째 에는 0 이들어가 0이 뒤로 이동한 것을 확인할 수 있다.
그리고 nIdx++ 가 되기에 다른 숫자의 순서는 그대로 두며 0만 뒤로 옮길 수 있다.
운영중인 카톡방입니다.
https://open.kakao.com/o/gsMhUFie
'LeetCode' 카테고리의 다른 글
162. Find Peak Element c++ 문제 (0) | 2022.06.21 |
---|---|
88. Merge Sorted Array c++ 문제 (0) | 2022.06.20 |
75. Sort Colors LeetCode C++ (0) | 2022.06.20 |
Leetcode 704번 Find Pivot Index 해설 (0) | 2022.06.19 |
Binary search LeetCode-704 문제 (0) | 2022.06.11 |
댓글