[LeetCode] Challenge log 561

561. Array Partition I
  1. quick sort O(2nlog2n) <= O(20000* (log2+ 100))
  2. ordered array trick O(n + max - min) = O(2n + 20000) <= 40000

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:

1
2
3
4
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].

Soulution:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# s1
class Solution:
def arrayPairSum(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
self.partition(nums, 0, len(nums)-1)
return sum([nums[i] for i in range(0, len(nums), 2)])

def partition(self, nums, l, r):
if l >= r: return
pivot = nums[r]
low = l
for i in range(l,r):
if nums[i] < pivot:
nums[i], nums[low] = nums[low], nums[i]
low += 1
nums[r], nums[low] = nums[low], nums[r]
self.partition(nums, l, low-1)
self.partition(nums, low + 1, r)
1
2
3
4
5
6
7
8
# one liner s1
class Solution:
def arrayPairSum(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
return sum(sorted(nums)[::2])
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#s2
class Solution:
def arrayPairSum(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
arr = [0] * 20001
res = 0
odd = True
for num in nums:
arr[num + 10000] += 1
for i in range(len(arr)):
while arr[i] > 0:
if odd: res += i - 10000
odd = not odd
arr[i] -= 1
return res
0%