[Python] 561. Array Partition I

2021. 2. 17. 19:49·study/LeetCode
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
'study/LeetCode' 카테고리의 다른 글
  • [Python] 2145. Count the Hidden Sequences
  • [Python] 238. Product of Array Except Self
  • [Python] 15. Two Sum
  • [Python] 1. Two Sum
bbooo
bbooo
  • bbooo
    bbooo
    bbooo
  • 전체
    오늘
    어제
    • 분류 전체보기 (142)
      • study (61)
        • 백준(BOJ) (34)
        • Programmers (15)
        • LeetCode (9)
      • AI (4)
        • Paper (0)
      • SSAC X IFFEL (4)
        • DeepML (1)
        • 밑바닥 부터 시작하는 딥러닝 (2)
      • 회고 (46)
      • Error (10)
      • Setting (15)
  • 블로그 메뉴

    • 홈
    • 태그
    • 글쓰기
    • 관리
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    파이썬 과제 진행하기
    백트래킹
    python 석유시추
    파이썬 석유시추
    set
    항해99
    sequence item 0: expected str instance int found
    파이썬
    99클럽
    풀이 실패
    Counter
    문자열을 원하는 길이로
    그리디 알고리즘
    백준
    프로그래머스 석유시추
    typeerror: sequence item 0: expected str instance int found
    docker
    vscode
    LeetCode
    programmers 석유시추
    두 포인터
    투포인터
    브루트포스
    sort
    python 과제 진행하기
    백준 2470
    개발자 취업
    코딩테스트 준비
    programmers 과제 진행하기
    Til
  • 최근 댓글

  • hELLO· Designed By정상우.v4.10.3
bbooo
[Python] 561. Array Partition I
상단으로

티스토리툴바