You are given an integer array digits
, where each element is a digit. The array may contain duplicates.
You need to find all the unique integers that follow the given requirements:
- The integer consists of the concatenation of three elements from
digits
in any arbitrary order. - The integer does not have leading zeros.
- The integer is even.
For example, if the given digits
were [1, 2, 3]
, integers 132
and 312
follow the requirements.
Return a sorted array of the unique integers.
Example 1:
Input: digits = [2,1,3,0] Output: [102,120,130,132,210,230,302,310,312,320] Explanation: All the possible integers that follow the requirements are in the output array. Notice that there are no odd integers or integers with leading zeros.
Example 2:
Input: digits = [2,2,8,8,2] Output: [222,228,282,288,822,828,882] Explanation: The same digit can be used as many times as it appears in digits. In this example, the digit 8 is used twice each time in 288, 828, and 882.
Example 3:
Input: digits = [3,7,5] Output: [] Explanation: No even integers can be formed using the given digits.
Constraints:
3 <= digits.length <= 100
0 <= digits[i] <= 9
这题虽然是enumeration的题,但是最简单的解法并不是enumeration的常规解法。因为题目限制了是三位数的偶数,那我们就可以强行遍历从100到999之间的所有偶数,记下给定数组中每个数字出现的次数,和这个三位数中每个数字出现的次数,相比较如果出现的次数更少,那就是最后的结果。这样生成出来的数,顺序也是sorted order,非常优秀。
class Solution {
public int[] findEvenNumbers(int[] digits) {
List<Integer> resultList = new ArrayList<>();
int[] digitFreq = new int[10];
for (int i = 0; i < digits.length; i++) {
digitFreq[digits[i]]++;
}
for (int i = 100; i < 999; i += 2) {
int[] currFreq = new int[10];
int curr = i;
while (curr != 0) {
currFreq[curr % 10]++;
curr /= 10;
}
boolean found = true;
for (int j = 0; j < 10; j++) {
if (digitFreq[j] < currFreq[j]) {
found = false;
break;
}
}
if (found) {
resultList.add(i);
}
}
int[] result = new int[resultList.size()];
for (int i = 0; i < resultList.size(); i++) {
result[i] = resultList.get(i);
}
return result;
}
}
然后还有人用真正enumeration的做法:LeetCode - The World's Leading Online Programming Learning Platform
等下次认真学习了enumeration以后再来看吧。留个坑先。