[LeetCode] 561. Array Partition I

 

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

 

 

 

 

💻 코드 (Java)

package org.kyhslam.leetCode;

import java.util.ArrayList;
import java.util.Arrays;

public class leet_561 {

    public static int arrayPairSum(int[] nums) {

        int sum = 0;

        Arrays.sort(nums);
        System.out.println(Arrays.toString(nums));

        ArrayList<Integer> a = new ArrayList<>();
        int left = 0;

        while (left < nums.length) {
            a.add(nums[left++]);

            if (a.size() == 2) {
                int x = a.get(0);
                int y = a.get(1);
                sum += Math.min(x, y);
                a.clear();
            }
        }

        System.out.println("sum = " + sum);
        return sum;
    }

    public static void main(String[] args) {
        int[] nums = {6,2,6,5,1,2}; // {1,4,3,2};

        arrayPairSum(nums);
    }
}

💻 코드 (Python)

from typing import List

class solution:
    def arrayPairSum(self, nums: List[int]) -> int:
        sum = 0;
        pair = []
        nums.sort() # 오름차순

        for n in nums:
            # 앞에서부터 오름차순으로 페어를 만들어서 합 계산
            pair.append(n)
            if len(pair) == 2:
                sum += min(pair)
                pair = []

        # print(sum)
        return sum

    def arrayPairSum2(self, nums: List[int]) -> int:
        sum = 0
        nums.sort()

        for i, n in enumerate(nums):
            print(i, n)
            if (i % 2) == 0:
                sum += n

        return sum


# nums = [1, 4, 3, 2]
nums = [6,2,6,5,1,2]

ss = solution()
#ss.arrayPairSum(nums)

ss.arrayPairSum2(nums)

 

댓글

Designed by JB FACTORY