Ai
1 Star 2 Fork 5

LilithSangreal/LeetCode-Solutions

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
array-partition-i.cpp 849 Bytes
一键复制 编辑 原始数据 按行查看 历史
kamyu 提交于 2017-12-09 21:55 +08:00 . Update array-partition-i.cpp
// Time: O(r), r is the range size of the integers
// Space: O(r)
class Solution {
public:
int arrayPairSum(vector<int>& nums) {
const auto LEFT = -10000;
const auto RIGHT = 10000;
vector<int> lookup(RIGHT - LEFT + 1, 0);
for (const auto& num: nums) {
++lookup[num - LEFT];
}
auto r = 0, result = 0;
for (int i = LEFT; i <= RIGHT; ++i) {
result += (lookup[i - LEFT] + 1 - r) / 2 * i;
r = (lookup[i - LEFT] + r) % 2;
}
return result;
}
};
// Time: O(nlogn)
// Space: O(1)
class Solution2 {
public:
int arrayPairSum(vector<int>& nums) {
sort(nums.begin(), nums.end());
auto result = 0;
for (auto i = 0; i < nums.size(); i += 2) {
result += nums[i];
}
return result;
}
};
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/LilithSangreal/LeetCode-Solutions.git
git@gitee.com:LilithSangreal/LeetCode-Solutions.git
LilithSangreal
LeetCode-Solutions
LeetCode-Solutions
master

搜索帮助