일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- 머신러닝
- GenerativeAI
- gcp
- 파이썬기초
- 코드업파이썬
- 코드업
- nlp
- 투포인터
- 파이썬
- 알고리즘
- Python3
- 리트코드
- 클라우드
- TwoPointer
- GenAI
- 생성형AI
- 데이터사이언스
- C#
- 파이썬알고리즘
- Azure
- 파이썬기초100제
- 빅데이터
- 자연어처리
- Microsoft
- 구글퀵랩
- codeup
- LeetCode
- Python
- 릿코드
- Blazor
Archives
- Today
- Total
Tech for good
[Leetcode/Two Pointer] 283. Move Zeroes 본문
class Solution:
def moveZeroes(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
non_zero_index = 0
# 배열을 처음부터 끝까지 순회하면서 0이 아닌 요소를 앞으로 이동
for i in range(len(nums)):
if nums[i] != 0:
# 현재 숫자(nums[i])와 non_zero_index 위치의 숫자를 스왑
nums[non_zero_index], nums[i] = nums[i], nums[non_zero_index]
non_zero_index += 1 # 0이 아닌 숫자를 배치할 다음 위치 증가
설명
- Two Pointer 사용:
- non_zero_index: 0이 아닌 값을 배치할 위치를 가리킴
- i: 리스트를 순회하면서 0이 아닌 값을 찾는 인덱스
- 순차적으로 배열을 탐색하면서 0이 아닌 값을 앞으로 이동:
- nums[i]가 0이 아니면 non_zero_index 위치와 swap
- swap이 이루어지면 non_zero_index를 증가시켜 다음 0이 아닌 값이 배치될 위치를 업데이트
- 시간복잡도:
- O(n), 한 번의 순회로 해결 가능
- 공간복잡도:
- O(1), 추가적인 배열을 사용하지 않음 (in-place 변경)
https://leetcode.com/problems/move-zeroes/description/
'IT > Computer Science' 카테고리의 다른 글
[Leetcode/Hash Map+Sorting] 3167. Better Compression of String (0) | 2025.02.17 |
---|---|
[Leetcode/Two Pointer] 75. Sort Colors (0) | 2025.02.16 |
[Leetcode/Two Pointer] 19. Remove Nth Node From End of List (0) | 2025.02.15 |
[Leetcode/Hash Set] 653. Two Sum IV - Input is a BST (0) | 2025.02.15 |
[Leetcode/Two Pointer] 653. Two Sum IV - Input is a BST (0) | 2025.02.15 |