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
- 파이썬릿코드
- 잇츠디모
- python Leetcode
- LeetCode
- 코틀린기초
- leetcode 풀기
- 파이썬 프로그래머스
- python priority queue
- leetcode풀이
- 알고리즘풀기
- 상가수익률계산기
- 릿코드풀기
- python xor
- 파이썬 알고리즘 풀기
- leetcode풀기
- python sorted
- 파이썬알고리즘풀기
- 릿코드 풀기
- 릿코드 파이썬
- 알고리즘풀이
- python zip_longest
- 파이썬 알고리즘
- 파이썬 릿코드
- python 릿코드
- 릿코드풀이
- 릿코드
- binary search
- 파이썬릿코드풀기
- python 알고리즘
- 파이썬알고리즘
Archives
- Today
- Total
소프트웨어에 대한 모든 것
LeetCode 풀기 - 283. Move Zeroes 본문
반응형
283. Move Zeroes
https://leetcode.com/problems/move-zeroes/
Move Zeroes - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
문제)
솔루션1)
연산 수행 속도를 최소화하는 것이 follow up에 명시되어 있네요.
문제 자체는 쉬웠는데 속도가 너무 느리네요.
시간 복잡도가 O(n^2)입니다.
풀이 전략:
1) 배열에서 0에 해당하는 모든 인덱스를 검색
2) 0에 해당하는 요소의 마지막에 있는 것 부터 뒤로 swap하면서 옮겨간다.
class Solution:
def moveZeroes(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
# zero 인덱스 찾기
locate = lambda nums, target: [idx for idx, n in enumerate(nums) if n == target]
zero_indices = locate(nums, 0)
# 제일 뒤 부터 0을 배치하는 방식
last_zero_index = len(nums) - 1
for zero_index in reversed(zero_indices):
for i in range(zero_index, last_zero_index):
# swap
nums[i], nums[i+1] = nums[i+1], nums[i]
last_zero_index -= 1
솔루션2)
leetcode의 discuss를 보니 신박하게 풀었네요.
시간복잡도가 O(n), 공간복잡도 O(1)입니다.
class Solution:
def moveZeroes(self, nums: List[int]) -> None:
zero_idx = 0
for i in range(len(nums)):
if nums[i] != 0:
nums[i], nums[zero_idx] = nums[zero_idx], nums[i]
zero_idx += 1
솔루션3)
인터뷰에는 적합하지는 않지만 직관적이고 단순하게 아래와 같이도 풀 수 있습니다.
0의 수만큼 삭제를 수행하고 배열 뒤에 0를 추가합니다.
class Solution:
def moveZeroes(self, nums: List[int]) -> None:
zero_count = nums.count(0)
for _ in range(zero_count):
nums.remove(0)
nums.append(0)
반응형
'알고리즘 > LeetCode' 카테고리의 다른 글
LeetCode 풀기 - 1413. Minimum Value to Get Positive Step by Step Sum (0) | 2021.11.12 |
---|---|
LeetCode 풀기 - 167. Two Sum II - Input Array Is Sorted (0) | 2021.11.12 |
LeetCode 풀기 - 46. Permutations (0) | 2021.11.11 |
LeetCode 풀기 - 43. Multiply Strings (0) | 2021.11.10 |
LeetCode 풀기 - 1704. Determine if String Halves Are Alike (0) | 2021.11.10 |
Comments