| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 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
- 코딩
- 백준
- 구현
- T tree
- 27448
- 코복장
- dfs
- 2247
- BFS
- 모두의 꿈
- 부분수열의 합2
- 정답코드
- 다이나믹 프로그래밍
- 스펨메일 분류
- python
- 코딩테스트
- dp
- 파이썬
- ps
- 아니메컵
- 17070
- lgb
- 실질적 약수
- 딥러닝
- 정렬
- C
- 힙 정렬
- populating next right pointers in each node
- 샤논 엔트로피
- 코테
Archives
- Today
- Total
코딩복습장
LeetCode: Maximum Gap 본문
728x90
Given an integer array nums, return the maximum difference between two successive elements in its sorted form. If the array contains less than two elements, return 0.
You must write an algorithm that runs in linear time and uses linear extra space.
Example 1:
Input: nums = [3,6,9,1]
Output: 3
Explanation: The sorted form of the array is [1,3,6,9], either (3,6) or (6,9) has the maximum difference 3.
Example 2:
Input: nums = [10]
Output: 0
Explanation: The array contains less than 2 elements, therefore return 0.
Constraints:
- 1 <= nums.length <= 105
- 0 <= nums[i] <= 109
한 문제를 풀어보았다.
난이도가 medium 이길래 생각보다 오래 걸릴 것이라고 생각했지만, 너무 쉽게 풀렸다.
푸는 방법은 매우 간단하다.
list를 정렬하고, 정렬된 list에서 연속된 숫자의 차이 절댓값을 계속 비교해나가면 된다.

구현코드
class Solution(object):
def maximumGap(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if len(nums) <= 1:
return 0
nums.sort()
res = 0
for i in range(1, len(nums)):
if res < abs(nums[i-1] - nums[i]):
res = abs(nums[i-1] - nums[i])
return res728x90
'코딩 테스트 > python(파이썬)' 카테고리의 다른 글
| LeetCode: Longest Common Prefix (0) | 2025.06.03 |
|---|---|
| LeetCode: Valid Parentheses (0) | 2025.06.03 |
| 백준: 구슬 탈출 2 (13460번) (2) | 2025.05.30 |
| LeetCode: Populating Next Right Pointers in Each Node (0) | 2025.05.29 |
| LeetCode: Merge Sorted Array (0) | 2025.05.26 |
Comments