Solution Code
C#
public class Solution {
public int ArrayPairSum(int[] nums) {
int n = nums.Length, answer = 0;
Array.Sort(nums);
for (int i = 0; i < n; i += 2)
answer += nums[i];
return answer;
}
}
C++
class Solution {
public:
int arrayPairSum(vector<int>& nums) {
int n = nums.size(), answer = 0;
sort(nums.begin(), nums.end());
for (int i = 0; i < n; i += 2)
answer += nums[i];
return answer;
}
};
Java
class Solution {
public int arrayPairSum(int[] nums) {
int n = nums.length, answer = 0;
Arrays.sort(nums);
for (int i = 0; i < n; i += 2)
answer += nums[i];
return answer;
}
}
Python
class Solution(object):
def arrayPairSum(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
nums.sort()
return sum([i for i in nums[::2]])
Ruby
# @param {Integer[]} nums
# @return {Integer}
def array_pair_sum(nums)
nums.sort!
(nums.select!.with_index { |_,i| i.even? }).sum
end
Resources