[LeetCode] 561. Array Partition I

2021. 1. 10. 21:28Problem Solving/LeetCode

https://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

내 풀이 1

class Solution:
    def arrayPairSum(self, nums: List[int]) -> int:
        nums.sort(reverse=True)
        sum = 0
        for i in range(1, len(nums), 2):
            sum += nums[i]
        return sum

내림차순으로 정렬 -> 두 칸씩 건너뛰며 짝수항 더하기

내 풀이 2

class Solution:
    def arrayPairSum(self, nums: List[int]) -> int:
        nums.sort()
        return sum(nums[0::2])

짝수항만 슬라이싱 한 것의 합

참고

파이썬 알고리즘 인터뷰
국내도서
저자 : 박상길
출판 : 책만 2020.07.15
상세보기
반응형