当前位置:网站首页>LeetCode 2342. Digital and equal number of one of the biggest and
LeetCode 2342. Digital and equal number of one of the biggest and
2022-07-30 01:28:00 【Michael amin】
1. 题目
给你一个下标从 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 <= 10^5
1 <= nums[i] <= 10^9
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/max-sum-of-a-pair-with-equal-sum-of-digits
著作权归领扣网络所有.商业转载请联系官方授权,非商业转载请注明出处.
2. 解题
- 和作为 key,值为数字的 list,之后对 list 排序,取最大的2个
class Solution:
def maximumSum(self, nums: List[int]) -> int:
def bitsum(x):
s = 0
while x:
s += x%10
x //= 10
return s
d = defaultdict(list)
for x in nums:
d[bitsum(x)].append(x)
ans = -1
for k, v in d.items():
if len(v) > 1:
v.sort()
ans = max(ans, sum(v[-2:]))
return ans
384 ms 27.4 MB Python3
- 排序,can be changed to keep only the largest two
class Solution:
def maximumSum(self, nums: List[int]) -> int:
def bitsum(x):
s = 0
while x:
s += x%10
x //= 10
return s
d = defaultdict(list)
for x in nums:
s = bitsum(x)
if len(d[s]) <= 1:
d[s].append(x)
else:
arr = d[s]
if arr[0] > arr[1]:
arr[0], arr[1] = arr[1], arr[0]
if x > arr[0]:
d[s] = [x, arr[1]]
ans = -1
for k, v in d.items():
if len(v) > 1:
ans = max(ans, sum(v))
return ans
372 ms 26.5 MB Python3
我的CSDN博客地址 https://michael.blog.csdn.net/
长按或扫码关注我的公众号(Michael阿明),一起加油、一起学习进步!
边栏推荐
猜你喜欢

STM32——OLED显示实验

Baidu Intelligent Cloud Zhangmiao: Detailed explanation of enterprise-level seven-layer load balancing open source software BFE

【MySQL必知必会】 范式 | ER模型

【LeetCode每日一题】——637.二叉树的层平均值

液压滑环的应用介绍

Selenium上传文件有多少种方式?不信你有我全

Huawei's "genius boy" Zhihui Jun has made a new work, creating a "customized" smart keyboard from scratch

my creative day

【MySQL系列】MySQL数据库基础

CMake Tutorial Tour (1)_Basic starting point
随机推荐
Unity笔记——FairyGUI
Talk about the construction of the performance test environment
面试题:手写Promise
How to realize the frame selection of objects in canvas (6)
SwiftUI SQLite数据库存储使用教程大合集(2022年版)
帽式滑环的工作原理
MySQL高级篇(高阳)建表sql语句大全
新型LaaS协议Elephant Swap给ePLATO提供可持续溢价空间
什么专业越老越吃香?
Interviews with big factories under the trend of layoffs: "ByteDance"
Minimum number to rotate array
自学HarmonyOS应用开发(49)- 引入地图功能
Object.freeze() learning
[Flutter] Flutter preloading of mixed development solves the problem of slow page loading for the first time
泰克Tektronix示波器软件TDS1012|TDS2002|TDS2004上位机软件NS-Scope
9 common mistakes testers fall into
CMake Tutorial Tour (1)_Basic starting point
Finding a 2D Array
TCP/IP 常见问题
软考 --- 数据库(5)数据库控制