当前位置:网站首页>2342. 数位和相等数对的最大和 哈希优化
2342. 数位和相等数对的最大和 哈希优化
2022-08-02 14:11:00 【超级码力奥】
给你一个下标从 0 开始的数组 nums ,数组中的元素都是 正 整数。请你选出两个下标 i 和 j(i != j),且 nums[i] 的数位和 与 nums[j] 的数位和相等。
请你找出所有满足条件的下标 i 和 j ,找出并返回 nums[i] + nums[j] 可以得到的 最大值 。
示例 1:
输入:nums = [18,43,36,13,7]
输出:54
解释:满足条件的数对 (i, j) 为:
- (0, 2) ,两个数字的数位和都是 9 ,相加得到 18 + 36 = 54 。
- (1, 4) ,两个数字的数位和都是 7 ,相加得到 43 + 7 = 50 。
所以可以获得的最大和是 54 。
示例 2:
输入:nums = [10,12,19,14]
输出:-1
解释:不存在满足条件的数对,返回 -1 。
提示:
1 <= nums.length <= 105
1 <= nums[i] <= 109
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/max-sum-of-a-pair-with-equal-sum-of-digits
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。.
最初的想法:
枚举,两个和两个找是n^2,然后求各位的数字之和时间为logn,总的时间复杂度是O(n ^ 2logn)。所以要优化。
优化
对于数字之和,使用哈希表维护一个可以家出来他的最大值。然后从小到大枚举nums,更新结果
时间复杂度优化到O(nlogn)
class Solution {
public:
int maximumSum(vector<int>& nums) {
int res = -1;
unordered_map<int, int> hash;
for(auto x: nums){
int s = 0, y = x;
while(y) s += y % 10, y /= 10;
// 如果hash里边没有这个索引,默认返回0
if(hash.count(s)) res = max(res, x + hash[s]);
hash[s] = max(hash[s], x);
}
return res;
}
};
边栏推荐
- The SSE instructions into ARM NEON
- A clean start Windows 7?How to load only the basic service start Windows 7 system
- MATLAB图形加标注的基本方法入门简介
- Please make sure you have the correct access rights and the repository exists. Problem solved
- 第三十章:普通树的存储和遍历
- pytorch模型转libtorch和onnx格式的通用代码
- Failed to install using npx -p @storybook/cli sb init, build a dedicated storybook by hand
- MATLAB绘图函数fplot详解
- mysql学习总结 & 索引
- How to simulate 1/3 probability with coins, and arbitrary probability?
猜你喜欢

MATLAB绘制平面填充图入门详解

开心一下,9/28名场面合集

What should I do if the Win10 system sets the application identity to automatically prompt for access denied?

win10怎么设置不睡眠熄屏?win10设置永不睡眠的方法

使用 腾讯云搭建一个个人博客

What are IPV4 and IPV6?

Win7 encounters an error and cannot boot into the desktop normally, how to solve it?

总结计算机网络超全面试题

软件测试基础知识(背)

网络安全抓包
随机推荐
Project: combing the database table
深入理解Golang之Map
Detailed explanation of MATLAB drawing function plot
Win10系统设置application identity自动提示拒绝访问怎么办
C语言函数参数传递模式入门详解
A clean start Windows 7?How to load only the basic service start Windows 7 system
The SSE instructions into ARM NEON
flink+sklearn——使用jpmml实现flink上的机器学习模型部署
Open the door of electricity "Circuit" (1): voltage, current, reference direction
STM32LL库使用——SPI通信
关于c语言的调试技巧
如何用硬币模拟1/3的概率,以及任意概率?
专硕与学硕
倍增和稀疏表
pygame绘制弧线
背包问题-动态规划-理论篇
pygame图像连续旋转
Happy, 9/28 scene collection
二叉树遍历之后序遍历(非递归、递归)入门详解
求解斐波那契数列的若干方法