当前位置:网站首页>LeetCode_2342_数位和相等数对的最大和
LeetCode_2342_数位和相等数对的最大和
2022-07-23 07:02:00 【Fitz1318】
题目链接
题目描述
给你一个下标从 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 <= 1051 <= nums[i] <= 109
解题思路
- 首先对数组进行排序,然后写一个函数获得每个整数的各个数位和
- 初始最大值是
-1,遍历数组,使用哈希表记录,每次如果更新数位和时,就可以直接放入当前的nums[i],来确保放入的和得到的都是当前最大的
AC代码
class Solution {
public int maximumSum(int[] nums) {
Arrays.sort(nums);
int ans = -1;
HashMap<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
int k = getSum(nums[i]);
if (map.containsKey(k)) {
ans = Math.max(nums[i] + map.get(k), ans);
}
map.put(k, nums[i]);
}
return ans;
}
private static int getSum(int n) {
int sum = 0;
while (n > 0) {
int tmp = n % 10;
sum += tmp;
n = n / 10;
}
return sum;
}
}
边栏推荐
- ROS2自学笔记:URDF机器人建模
- Typora 修改表格宽度
- ROS中引用和输出消息类型
- docker mysql
- Unity关于本地加载图片涉及webrequest或者byte
- PHP获取当前时间戳三位毫秒 - 毫秒时间戳
- Point target simulation of SAR imaging (III) -- Analysis of simulation results
- ES6——周考题
- Optimising a 3D convolutional neural network for head and neck computed tomography segmentation with
- 数据库系统原理与应用教程(048)—— MySQL 查询(十):自连接查询
猜你喜欢

docker redis

Matplotlib- implement common probability distributions

2022暑假软件创新实验室集训 项目实战1

Special topic of MIMO Radar (0) - General Chapter

【深入浅出玩转FPGA学习10------简单的Testbench设计】

ES6——周考题

浅谈Anroid设备的CPU类型以及so文件的放置目录

Charles' bag grabbing tool test practice

Ros2 self study notes: URDF robot modeling

Kept dual machine hot standby
随机推荐
Ros2 self study notes: gazebo physical simulation platform
解决MySQL向表中增加数据插入中文乱码问题
Special topic of MIMO Radar (0) - General Chapter
Chapter II relational database after class exercises
C # make a simple browser
【记录】golang跨平台编译
【可視化調度軟件】上海道寧為SMB組織帶來NETRONIC下載、試用、教程
Notes on the ninth day
Day 11 notes
Introduction to radar part vii 3 formation and processing of SAR image
Reference and output message types in ROS
数据库系统原理与应用教程(051)—— MySQL 查询(十三):DML 语句中使用查询
php连接sql server
数据库系统原理与应用教程(041)—— MySQL 查询(三):设置查询条件
高中语文教资考试大纲
Power bi - Comprehensive Application
About this pointer
PHP获取当前时间戳三位毫秒 - 毫秒时间戳
ROS中引用和输出消息类型
基于BIM+3DGIS的智慧城市基础设施管理