728x90
leetcode.com/problems/array-partition-i/
Array Partition I - 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
풀이
from typing import *
class Solution:
def arrayPairSum(self, nums: List[int]) -> int:
# 순서대로 나열을 해서 짝수번째 수만 더하면 됨
nums = sorted(nums)
i, sum = 0, 0
print(nums)
while i < len(nums):
sum += nums[i]
i += 2
return sum
시간을 단축시키기 위해
1. 슬라이싱 이용
구문[::2]는 2칸씩 건너뛰므로 짝수번 째를 계산하는 것과 동일함.
def arrayPairSum(self, nums: List[int]) -> int:
return sum(sorted(nums)[::2])
728x90
'study > LeetCode' 카테고리의 다른 글
[Python] 2145. Count the Hidden Sequences (1) | 2024.06.16 |
---|---|
[Python] 238. Product of Array Except Self (0) | 2021.03.13 |
[Python] 15. Two Sum (0) | 2021.02.17 |
[Python] 1. Two Sum (0) | 2021.01.22 |
[Python] 819. Most Common Word (0) | 2021.01.15 |