LeetCode 561. Array Partition I

来源:互联网 发布:哪些化妆品比较好知乎 编辑:程序博客网 时间:2024/06/05 03:37

Description

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.

Example 1:

Input: [1,4,3,2]
Output: 4
Explanation: 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].

Analysis

核心思想:容易知道,最佳方案是将数值上相邻的两个数字组为一个group,选每个group小的数字求和,即为最后答案。简单地反证可以验证这一思路。

那么差异就出现在实现方法上。

方法一:对这2n个整数进行排序,排序后求和公式为

i=0i<n/2nums[2i]

方法二:由于题目中给出了数字的范围,不太大,可以直接用哈希表来记录数字的出现次数,自然而然实现排序效果,但时间复杂度降到了O(n)

Code

class Solution {public:    int arrayPairSum(vector<int>& nums) {        int n = nums.size();        sort(nums.begin(),nums.end());        int sum = 0;        for (int i = 0; i < n; i+=2){            sum += nums[i];        }        return sum;    }};

Appendix

  • Link: https://leetcode.com/problems/array-partition-i/
  • Run Time:
    • Version 1: 83ms
0 0
原创粉丝点击