알고리즘/해결

LeetCode561. Array Partition I

언클린 2020. 3. 25. 21:05
728x90

1. 문제(원본)

Given an array of 2n integers, your task is to group these integers into n pairs of integer, say (a1, b1), (a2, b2), ..., (an, bn) which makes sum of min(ai, bi) for all i from 1 to n as large as possible.

Example 1:

Input: [1,4,3,2] Output: 4 Explanation: n is 2, and the maximum sum of pairs is 4 = min(1, 2) + min(3, 4).

Note:

  1. n is a positive integer, which is in the range of [1, 10000].
  2. All the integers in the array will be in the range of [-10000, 10000].

2. 문제

주어진 2N의 배열에서 인덱스를 두개씩 짝 지어 가장 큰 최솟값들의 합을 구하라

3. 나의 답

class Solution {

    func arrayPairSum(_ nums: [Int]) -> Int {

        var result = 0

        let sortArray = nums.sorted()

        for index in 0..<sortArray.count where index % 2 == 0 {

            result = result + min(sortArray[index], sortArray[index + 1])

            print(result)

        }

        return result

    }

}

4. 다른 유저의 답

#1

class Solution {

    func arrayPairSum(_ nums: [Int]) -> Int {

        var sum = 0

        for (index, value) in nums.sorted().enumerated() {

            if index % 2 == 0 { sum += value }

        }

        return sum

    }

}

5. 마무리

LeetCode를 공부하면서 느낀 것이 나름 발상의 전환을 해서 구했다고 생각하는데 몇 몇 유저들의 답은 정말 확실하게 더욱 깔끔하게 구했다. 다양한 답도 접할 수 있는 것이 좋은 것 같다.

728x90

'알고리즘 > 해결' 카테고리의 다른 글

LeetCode557. Reverse Words in a String III  (0) 2020.03.31
LeetCode942. DI String Match  (0) 2020.03.25
LeetCode1051. Height Checker  (0) 2020.03.25
LeetCode728. Self Dividing Numbers  (0) 2020.03.25
LeetCode700. Search in a Binary Search Tree  (0) 2020.03.23