其他分享
首页 > 其他分享> > LeetCode 2094. Finding 3-Digit Even Numbers

LeetCode 2094. Finding 3-Digit Even Numbers

作者:互联网

原题链接在这里:https://leetcode.com/problems/finding-3-digit-even-numbers/

题目:

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:

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:

题解:

From 100 to 999, for each even number i, check its digits all appear in the map.

The map is precalculated by digits array.

Time Complexity: O(n). n = 900/2.

Space: O(1).

AC Java:

 1 class Solution {
 2     public int[] findEvenNumbers(int[] digits) {
 3         int [] count = new int[10];
 4         for(int d : digits){
 5             count[d]++;
 6         }
 7         
 8         List<Integer> list = new ArrayList<>();
 9         for(int i = 100; i < 1000; i+=2){
10             int a = i % 10; 
11             int b = (i / 10) % 10;
12             int c = i / 100;
13             
14             count[a]--;
15             count[b]--;
16             count[c]--;
17             if(count[a] >=0 && count[b] >= 0 && count[c] >= 0){
18                 list.add(i);
19             }
20             
21             count[a]++;
22             count[b]++;
23             count[c]++;
24         }
25         
26         int [] res = new int[list.size()];
27         for(int i = 0; i < res.length; i++){
28             res[i] = list.get(i);
29         }
30         
31         return res;
32     }
33 }

 

标签:Even,digits,Digit,integers,int,++,count,2094,array
来源: https://www.cnblogs.com/Dylan-Java-NYC/p/16560422.html