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 | 31 |
Tags
- 처음 만나는 AI 수학 with Python
- 자바편
- 친절한SQL튜닝
- 처음 만나는 AI수학 with Python
- 자료구조와 함께 배우는 알고리즘 입문
- resttemplate
- d
- Kernighan의 C언어 프로그래밍
- 코드로배우는스프링부트웹프로젝트
- 네트워크 설정
- 스프링 시큐리티
- 코드로배우는스프링웹프로젝트
- 선형대수
- ㅒ
- 이터레이터
- 데비안
- 스프링부트핵심가이드
- baeldung
- 티스토리 쿠키 삭제
- iterator
- 리눅스
- /etc/network/interfaces
- 서버설정
- 자료구조와함께배우는알고리즘입문
- 페이징
- network configuration
- 알파회계
- 구멍가게코딩단
- GIT
- 목록처리
Archives
- Today
- Total
bright jazz music
283. 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: [1,3,12,0,0]
Example 2:
Input: nums = [0]
Output: [0]
Constraints:
1 <= nums.length <= 104
-231 <= nums[i] <= 231 - 1
Follow up: Could you minimize the total number of operations done?
/**
Do not return anything, modify nums in-place instead.
*/
// 접근 방법
//Two Pointer 방식을 사용
// left 포인터: 0이 아닌 요소를 배치할 위치
// right 포인터: 배열을 순회하면서 0이 아닌 요소를 찾음
function moveZeroes(nums: number[]): void {
let left = 0;
for(let right = 0; right < nums.length; right++) {
if(nums[right] !== 0) {
if(left !== right) {
[nums[left], nums[right]] = [nums[right], nums[left]]
}
// left는 "0이 아닌 요소가 들어갈 위치"를 가리킨다.
// right는 배열을 순회하면서 계속 증가한다.
// right가 0이 아닌 값을 만나면:
// 1. left와 right의 위치를 바꾼다 (만약 다르다면)
// 2. left를 증가시킨다 (다음 0이 아닌 값이 들어갈 자리로 이동)
left++;
}
}
// return nums
};
/* 아래와 같이 하는 게 풀어쓴 방식
var moveZeroes = function(nums) {
let left = 0; // 0이 아닌 요소를 배치할 위치
// 1단계: 0이 아닌 요소들을 앞으로 이동
for (let right = 0; right < nums.length; right++) {
if (nums[right] !== 0) {
nums[left] = nums[right];
left++;
}
}
// 2단계: 남은 위치를 0으로 채우기
for (let i = left; i < nums.length; i++) {
nums[i] = 0;
}
};
*/'Algorithm Practice > LeetCode' 카테고리의 다른 글
| 443. String Compression (0) | 2026.01.19 |
|---|---|
| 334. Increasing Triplet Subsequence (0) | 2026.01.17 |
| 238. Product of Array Except Self (0) | 2026.01.16 |
| 151. Reverse Words in a String (0) | 2026.01.15 |
| 345. Reverse Vowels of a String (0) | 2026.01.14 |
Comments