# [用Golang刷LeetCode之 3] 561. Array Partition I

miltonsun · · 5366 次点击 · · 开始浏览

# 题目

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.

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

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

# 代码

arrayPartition.go

``````package _561_Array_Partition1

import "sort"

func ArrayPairSum(nums []int) (minPairSum int) {
sort.Ints(nums)

for k, v := range nums {
if 0 == k%2 {
minPairSum += v
}
}
return minPairSum
}
``````

# 测试代码

arrayPartition_test.go

``````package _561_Array_Partition1

import "testing"

func Test_ArrayPairSum(t *testing.T) {

input := []int{1,4,3,2}

sum := ArrayPairSum(input)

if 4 == sum {
t.Logf("pass")
} else {
t.Errorf("fail, want 4, get %+v\n", sum)
}
}
``````

0 回复

• 请尽量让自己的回复能够对别人有帮助
• 支持 Markdown 格式, **粗体**、~~删除线~~、``单行代码``
• 支持 @ 本站用户；支持表情（输入 : 提示），见 Emoji cheat sheet
• 图片支持拖拽、截图粘贴等方式上传

# 题目

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.

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

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

# 代码

arrayPartition.go

``````package _561_Array_Partition1

import "sort"

func ArrayPairSum(nums []int) (minPairSum int) {
sort.Ints(nums)

for k, v := range nums {
if 0 == k%2 {
minPairSum += v
}
}
return minPairSum
}
``````

# 测试代码

arrayPartition_test.go

``````package _561_Array_Partition1

import "testing"

func Test_ArrayPairSum(t *testing.T) {

input := []int{1,4,3,2}

sum := ArrayPairSum(input)

if 4 == sum {
t.Logf("pass")
} else {
t.Errorf("fail, want 4, get %+v\n", sum)
}
}
``````