题目地址:
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)。