当前位置:网站首页>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;
}
};
边栏推荐
- MATLAB制作简易小动画入门详解
- Yolov5 official code reading - prior to transmission
- 二叉树遍历之后序遍历(非递归、递归)入门详解
- pytorch模型转libtorch和onnx格式的通用代码
- 第二十五章:一文掌握while循环
- Detailed explanation of MATLAB drawing function fplot
- 5. Transaction management
- What should I do if the Win10 system sets the application identity to automatically prompt for access denied?
- Mysql connection error solution
- 第三十二章:二叉树的存储与遍历
猜你喜欢

软件测试基础知识(背)

4. Publish Posts, Comment on Posts

Doubled and sparse tables

General syntax and usage instructions of SQL (picture and text)

STM32LL library - USART interrupt to receive variable length information

What should I do if Windows 10 cannot connect to the printer?Solutions for not using the printer

Do Windows 10 computers need antivirus software installed?

Detailed explanation of MATLAB drawing function fplot

第二十六章:二维数组

二叉树的遍历:递归法/ 迭代法/ 统一迭代法(强QAQ)
随机推荐
Do Windows 10 computers need antivirus software installed?
golang之GMP调度模型
二叉树创建之层次法入门详解
What is Win10 God Mode for?How to enable God Mode in Windows 10?
Win10电脑不能读取U盘怎么办?不识别U盘怎么解决?
Codeforces Round #624 (Div. 3)
TCP三次握手、四次挥手
Configure clangd for vscode
A clean start Windows 7?How to load only the basic service start Windows 7 system
利用plot_surface命令绘制复杂曲面入门详解
Based on the matrix calculation in the linear regression equation of the coefficient estimates
Summarize computer network super comprehensive test questions
Win10安装了固态硬盘还是有明显卡顿怎么办?
Win11 keeps popping up User Account Control how to fix it
Spark及相关生态组件安装配置——快速回忆
How to reinstall Win7 system with U disk?How to reinstall win7 using u disk?
推开机电的大门《电路》(一):电压,电流,参考方向
Open the door of power and electricity "Circuit" (2): Power Calculation and Judgment
将SSE指令转换为ARM NEON指令
Win7遇到错误无法正常开机进桌面怎么解决?