当前位置:网站首页>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阿明),一起加油、一起学习进步!
边栏推荐
- Detailed introduction to the usage of Nacos configuration center
- 【微服务~Nacos】Nacos服务提供者和服务消费者
- LeetCode / Scala - 无重复字符最长子串 ,最长回文子串
- go语言解决自定义header的跨域问题
- 百度智能云章淼:详解企业级七层负载均衡开源软件BFE
- 性能测试理论1 | 性能测试难点问题梳理
- 数据流图、数据字典
- exness: U.S. GDP shrinks, yen bounces back
- 【Flutter】Flutter inspector 工具使用详解,查看Flutter布局,widget树,调试界面等
- 多AZ双活容灾部署的云端系统架构设计说明书框架
猜你喜欢
随机推荐
npm ERR! code ENOTSUPnpm ERR! notsup Unsupported engine for [email protected]: wanted: {“n
nacos集群配置详解
CMake Tutorial 巡礼(1)_基础的起点
记笔记!电源自动测试系统测试电源纹波详细方法
我的创作纪念日
Running a Fabric Application
Performance Testing Theory 1 | Sorting out difficult problems in performance testing
Selenium上传文件有多少种方式?不信你有我全
Validation Framework-01
2022-07-29:一共有n个人,从左到右排列,依次编号0~n-1, h[i]是第i个人的身高, v[i]是第i个人的分数, 要求从左到右选出一个子序列,在这个子序列中的人,从左到右身高是不下降的。
FlutterBoost 3.0出现 Activity无法转换为ExclusiveAppComponent<Activity>的解决办法
推荐系统:用户“行为数据”的采集【使用Kafaka、Cassandra处理数据】【如果与业务数据重合,也需要独自采集】
自学HarmonyOS应用开发(53)- 获取当前位置
How many ways does Selenium upload files?I don't believe you have me
go语言解决自定义header的跨域问题
Huawei's "genius boy" Zhihui Jun has made a new work, creating a "customized" smart keyboard from scratch
泰克Tektronix示波器软件TDS520|TDS1001|TDS1002上位机软件NS-Scope
Navicat for mysql破解版安装
推荐系统:特征工程、常用特征
How Junior Testers Grow Fast







