Notice
Recent Posts
Recent Comments
Link
| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 1 | 2 | 3 | 4 | 5 | 6 | |
| 7 | 8 | 9 | 10 | 11 | 12 | 13 |
| 14 | 15 | 16 | 17 | 18 | 19 | 20 |
| 21 | 22 | 23 | 24 | 25 | 26 | 27 |
| 28 | 29 | 30 |
Tags
- 방통대
- javascript
- 깃
- sliding window
- 백준
- algorithm
- two pointers
- boj
- DP
- 이진탐색
- 코테
- 코딩
- 알고리즘
- 리트코드
- 완전탐색
- LeetCode
- 그리디
- Binary Search
- 자바스크립트
- 방송통신대학교
- 탐욕알고리즘
- Git
- greedy
- 투포인터
- 방송대
- dynamic programming
- 자바
- 컴퓨터과학과
- java
- it
Archives
- Today
- Total
개발이 취미인 주니어 기획자
[투포인터][JavaScript][LeetCode] #283. Move Zeros 본문
728x90
반응형
#투포인터 #EASY
Move Zeroes - LeetCode
Can you solve this real interview question? 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. E
leetcode.com
🌷 문제 설명
✏️ LeetCode 연습문제: Move Zeros
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.
🎃 제한 사항
1 <= nums.length <= 10^4
-2^31 <= nums[i] <= 2^31 - 1
입출력 예
| nums | result |
| [0, 1, 0, 3, 12] | [1, 3, 12, 0, 0] |
| [0] | [0] |
🌷 내 코드
1. 투포인터


var moveZeroes = function (nums) {
let left = 0;
let right = 1;
while (right < nums.length) {
if (nums[left] === 0 && nums[right] !== 0) { // 0 두 개가 연속으로 나오지 않는 경우
let temp = nums[left];
nums[left] = nums[right];
nums[right] = temp; // 0을 오른쪽으로 옮겨주고
left++; // 왼쪽도 다른 숫자로 갈 수 있도록 옮겨줌
}
if (nums[left] !== 0) { // 0이 아니면
left++; // 왼쪽도 오른쪽으로 옮겨줌
}
right++; // 두개 연속 0일 경우 pointer2를 오른쪽으로 옮겨줌
}
};
2. 무지성

var moveZeroes = function (nums) {
let zeroCnt = 0;
nums.forEach((n) => {
if (n === 0) {
zeroCnt++;
}
});
for (let i = 0; i < zeroCnt; i++) {
let idx = nums.indexOf(0);
nums.splice(idx, 1);
nums.push(0);
}
};
🌷 코멘트
투포인터는 알고리즘은 간단한데, 이외에도 문제에서 요구하는 걸 잘 읽어서 파악하는것이 중요한 것 같다
근데 파악이 안됨.. 예외케이스마다 다 틀리고 그것때문에 조건문을 계속 추가하는 듯;
머리로 잘 안 그려질 땐 주석으로라도 케이스를 눈으로나마 돌려가면서 고민해 보는 것두 나쁘지 않음 + 손으로 그리는건 더 좋고!
👉 미리 예외케이스를 생각해보려고 하자!
블로그 내용에 문제가 있다면 댓글 혹은 아래로 연락주세요!
~대가리 꽃밭인 디지털 노마드가 꿈이예요~
🧚♀️ Gyumin Lee
📧 gyumin.q.lee@gmail.com
qminlee723 - Overview
noob. qminlee723 has 8 repositories available. Follow their code on GitHub.
github.com
728x90
반응형
'문제 풀이 > 알고리즘 문제 풀이' 카테고리의 다른 글
| [투포인터][JavaScript][LeetCode] #557. Reverse Words in a String III (0) | 2023.04.01 |
|---|---|
| [투포인터][JavaScript][LeetCode] #344. Reverse String (0) | 2023.04.01 |
| [투포인터][JavaScript][LeetCode] #977. Squares of a Sorted Array (0) | 2023.03.30 |
| [이진탐색][JavaScript][LeetCode] #35. Search Insert Position (0) | 2023.03.30 |
| [이진탐색][JavaScript][LeetCode] #278. First Bad Version (0) | 2023.03.30 |