【leetcode数组和字符串】 数组拆分 I

给定长度为 2n 的数组, 你的任务是将这些数分成 n 对, 例如 (a1, b1), (a2, b2), …, (an, bn) ,使得从1 到 n 的 min(ai, bi) 总和最大。

示例 1:

输入: [1,4,3,2]
输出: 4

解释: n 等于 2, 最大总和为 4 = min(1, 2) + min(3, 4).

提示:
n 是正整数,范围在 [1, 10000].
数组中的元素范围在 [-10000, 10000].

C++题解

class Solution {
public:
    int arrayPairSum(vector<int>& nums) {
        sort(nums.begin(),nums.end());
        //偶数求和
        int res = 0;
        for(int i = 0; i < nums.size(); i+=2)
            res += nums[i];
        return res;
    }
};

总结:
1.迭代器

开始指针:vec.begin();
末尾指针:vec.end(); //指向最后一个元素的下一个位置
2.元素排序
#include algorithm
sort(vec.begin(), vec.end()); //采用的是从小到大的排序
3.偶数相加
4.双指针的运用

猜你喜欢

转载自blog.csdn.net/weixin_43046082/article/details/84892824