【Lintcode】1604. Maximum Sum of Two Numbers

题目地址:

https://www.lintcode.com/problem/maximum-sum-of-two-numbers/description

给定一个数组 A A A,里面选两个数,使得这两个数的所有位之和是相等的。问这两个数的和的最大值。如果选不出那样的两个数,则返回 − 1 -1 1。题目保证数组只包含正整数。

思路是哈希表。key是所有位之和,value可以开个长度为 2 2 2的数组,专门存数位和为key的数里前两大的数。然后再遍历哈希表的values,找到和最大的那个和即可。代码如下:

import java.util.HashMap;
import java.util.Map;

public class Solution {
    /**
     * @param A: An Integer array
     * @return: returns the maximum sum of two numbers
     */
    public int MaximumSum(int[] A) {
        // write your code here
        Map<Integer, int[]> map = new HashMap<>();
        for (int a : A) {
            int s = 0, tmp = a;
            // 求a的数位和
            while (tmp > 0) {
                s += tmp % 10;
                tmp /= 10;
            }
            
            map.putIfAbsent(s, new int[2]);
            int[] nums = map.get(s);
            // 打擂台
            if (a > nums[0]) {
                nums[1] = nums[0];
                nums[0] = a;
            } else if (a > nums[1]) {
                nums[1] = a;
            }
        }
    
    	// 把答案初始化为-1
        int res = -1;
        for (int[] nums : map.values()) {
        	// 如果小的数是0,说明没找到位数和相等的,跳过。否则更新答案
            if (nums[1] == 0) {
                continue;
            }         
            res = Math.max(res, nums[0] + nums[1]);
        }
        
        return res;
    }
}

时空复杂度 O ( n ) O(n) O(n)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值