LeetCode Solutions

561. Array Partition

Time: $O(n) \to O(n\log n)$$

Space: $O(n) \to O(1)$

			

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;
  }
};
			

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;
  }
}
			

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