LeetCode 2094. Finding 3-Digit Even Numbers

给定一个整数数组digits,需要找出所有符合以下要求的唯一整数:由digits中的三个元素按任意顺序连接组成,没有前导零,且为偶数。文章提供了两种解法,一种是通过遍历100到999之间的偶数,另一种是枚举组合方式。程序会返回所有满足条件的排序后的整数数组。
摘要由CSDN通过智能技术生成

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 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以后再来看吧。留个坑先。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值