561. Array Partition I; Difficulty : Easy

最优整数配对求和
本文介绍了一种算法问题,即如何从2n个整数中找出n组配对,使得每组配对中较小数值之和尽可能大。通过排序和选择偶数位置元素的方法给出了解决方案,并提供了C语言及Python实现。

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 = min(1, 2) + min(3, 4).

Note:
1. n is a positive integer, which is in the range of [1, 10000].
2. All the integers in the array will be in the range of [-10000, 10000].

算法分析:只要把相差最小的两个数分成一组即可。

C语言版

int cmp(const void *a, const void *b)
{
    return *(int *)a - *(int *)b;
}

int arrayPairSum(int* nums, int numsSize) {
    int i, sum = 0;
    qsort(nums, numsSize, sizeof(int), cmp);
    for(i = 0; i < numsSize; i += 2)
        sum += nums[i];

    return sum;
}

Python版

class Solution(object):
    def arrayPairSum(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        return sum(sorted(nums)[0:len(nums):2])
`memcpy` 函数原型为 `void* memcpy(void* dest, const void* src, size_t count);`,出现“没有匹配的重载函数”的错误提示,通常是因为传入的参数类型与 `memcpy` 函数要求的参数类型不兼容。 以下几种情况可能导致该问题及相应的解决办法: #### 1. `installObj_[i].partition` 类型问题 如果 `installObj_[i].partition` 不是 `void*` 或可以隐式转换为 `void*` 的类型,就会出现不匹配的问题。确保 `installObj_[i].partition` 是一个指向字符数组的指针。 示例代码如下: ```cpp #include <iostream> #include <string> #include <utility> #include <cstring> // 假设 installObj_ 元素的结构体定义 struct InstallObject { char partition[100]; // 确保有足够的空间 }; int main() { InstallObject installObj_[1]; std::pair<int, std::string> pair = {1, "example"}; auto it = &pair; constexpr int N = 1; // 进行 memcpy 操作 memcpy(installObj_[0].partition, std::get<N>(it->second).c_str(), strlen(std::get<N>(it->second).c_str())); // 确保字符串以 '\0' 结尾 installObj_[0].partition[strlen(std::get<N>(it->second).c_str())] = '\0'; std::cout << installObj_[0].partition << std::endl; return 0; } ``` #### 2. 缺少必要的头文件 确保包含了 `<cstring>` 头文件,因为 `memcpy` 和 `strlen` 函数都定义在这个头文件中。 #### 3. 目标缓冲区大小问题 要保证 `installObj_[i].partition` 有足够的空间来存储复制的数据,否则可能会导致缓冲区溢出。可以在复制完成后,手动添加字符串结束符 `'\0'`。 ```cpp memcpy(installObj_[i].partition, std::get<N>(it->second).c_str(), strlen(std::get<N>(it->second).c_str())); installObj_[i].partition[strlen(std::get<N>(it->second).c_str())] = '\0'; ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值