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
- 파이썬알고리즘풀기
- 상가수익률계산기
- 파이썬 알고리즘 풀기
- python 알고리즘
- leetcode 풀기
- python Leetcode
- 릿코드풀기
- 파이썬 알고리즘
- 파이썬릿코드
- python priority queue
- python xor
- 릿코드
- 파이썬 프로그래머스
- python zip_longest
- 코틀린기초
- python sorted
- 파이썬릿코드풀기
- 파이썬알고리즘
- 알고리즘풀이
- python 릿코드
- leetcode풀이
- 잇츠디모
- 릿코드 풀기
- LeetCode
- 릿코드풀이
- 릿코드 파이썬
- 파이썬 릿코드
- binary search
- leetcode풀기
- 알고리즘풀기
Archives
- Today
- Total
소프트웨어에 대한 모든 것
LeetCode 풀기 - 287. Find the Duplicate Number 본문
반응형
287. Find the Duplicate Number
https://leetcode.com/problems/find-the-duplicate-number/
Find the Duplicate Number - 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) 정렬
정렬한 다음에 순차적으로 중복된 숫자를 찾습니다.
class Solution:
def findDuplicate(self, nums):
nums = sorted(nums)
for i in range(len(nums) - 1):
if nums[i] == nums[i+1]:
return nums[i]
솔루션2) index
방문 했던 index에 -를 곱하게되면 두 번 방문한 index는 양수가 되므로 이를 이용해서 중복 숫자를 찾습니다.
class Solution:
def findDuplicate(self, nums):
for i in range(len(nums)):
idx = abs(nums[i]) - 1
nums[idx] *= -1
if nums[idx] > 0:
return abs(nums[i])
솔루션3) Floyd's cycle detection 알고리즘
플로이드 순환 알고리즘(Floyd's Tortoise & Hare)을 통해서 해당 문제를 해결할 수 있습니다.
class Solution:
def findDuplicate(self, nums):
slow = 0
fast = 0
while True:
# one step
slow = nums[slow]
# two step
fast = nums[nums[fast]]
if slow == fast:
break
slow2 = 0
while True:
# move one step both
slow = nums[slow]
slow2 = nums[slow2]
if slow == slow2:
break
return slow
함께 보면 좋은 글:
2022.03.03 - [알고리즘/알고리즘 Basic] - [파이썬] Floyd's Cycle Detection 알고리즘
[파이썬] Floyd's Cycle Detection 알고리즘
링크드 리스트에서 사이클(순환)을 찾는 알고리즘 중에 Floyd's Cycle Detection Algorithm (플로이드 순환 찾기 알고리즘)이 있습니다. 두 포인터를 이용해서 첫 번째 포인터는 one step 이동(slow pointer) 두..
wellsw.tistory.com
반응형
'알고리즘 > LeetCode' 카테고리의 다른 글
LeetCode 풀기 - 47. Permutations II (0) | 2022.03.08 |
---|---|
LeetCode 풀기 - 2181. Merge Nodes in Between Zeros (0) | 2022.03.04 |
LeetCode 풀기 - 34. Find First and Last Position of Element in Sorted Array (0) | 2022.02.28 |
LeetCode 풀기 - 64. Minimum Path Sum (0) | 2022.02.28 |
LeetCode 풀기 - 108. Convert Sorted Array to Binary Search Tree (0) | 2022.02.27 |
Comments