[C#][LeetCode][Easy] 561. Array Partition I

問題:

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.
心得:
看到這題我第一個反應就是去找linq有沒有辦法分割陣列,然後再加總= =
不過LINQ效能沒有很好,看到最佳解答有提供一個不錯的方法。

我的答案:

1
2
3
4
5
6
7
8
9

public class Solution {
public int ArrayPairSum(int[] nums) {
return nums.OrderBy(x => x)
.Select((x, index) => new { index, x })
.GroupBy(x => x.index / 2)
.Sum(x => x.Select(y => y.x).Min());
}
}

最佳解答:

1
2
3
4
5
6
7
8
9
10
11
12

public class Solution {
public int ArrayPairSum(int[] nums) {
Array.Sort(nums);
int result = 0;
for (int i = 0; i < nums.Length; i += 2)
{
result += nums[i];
}
return result;
}
}