Leetcode

Array Partition I

  • Time:O(n) \to O(n\log n)
  • Space:O(n) \to O(1)

C++

class Solution {
 public:
  int arrayPairSum(vector<int>& nums) {
    int ans = 0;

    sort(begin(nums), end(nums));

    for (int i = 0; i < nums.size(); i += 2)
      ans += nums[i];

    return ans;
  }
};

JAVA

class Solution {
  public int arrayPairSum(int[] nums) {
    int ans = 0;

    Arrays.sort(nums);

    for (int i = 0; i < nums.length; i += 2)
      ans += nums[i];

    return ans;
  }
}

Python

class Solution:
  def arrayPairSum(self, nums: List[int]) -> int:
    return sum(sorted(nums)[::2])