You are given an integer array digits
, where each element is a digit (0 - 9). The task is to return a sorted list of all unique 3-digit even numbers that can be formed using the digits in the array. Each digit from the array can only be used at most once in each 3-digit number.
Constraints according to the problem:
Output according to the problem:
set
to handle uniqueness.Given the constraints, this approach should be efficient and feasible.
#include <iostream>
#include <vector>
#include <set>
#include <algorithm>
std::vector<int> findEvenNumbers(std::vector<int>& digits) {
std::set<int> unique_even_numbers;
int n = digits.size();
for (int i = 0; i < n; ++i) {
if (digits[i] == 0) continue; // Skip zero for the hundreds place
for (int j = 0; j < n; ++j) {
if (j == i) continue; // Same index as the hundreds place
for (int k = 0; k < n; ++k) {
if (k == i || k == j) continue; // Same index as the hundreds or tens place
if (digits[k] % 2 == 0) { // Units place must be even
int number = digits[i] * 100 + digits[j] * 10 + digits[k];
unique_even_numbers.insert(number);
}
}
}
}
// Convert set to vector and sort
std::vector<int> result(unique_even_numbers.begin(), unique_even_numbers.end());
return result;
}
int main() {
std::vector<int> digits = {2, 1, 3, 0};
std::vector<int> result = findEvenNumbers(digits);
for (int num : result) {
std::cout << num << " ";
}
return 0;
}
This code effectively iterates through all combinations of three digits, ensuring the hundreds place is non-zero, the units place is even, and all digits are unique to the combination. These numbers are stored in a set to handle duplicates, and the final sorted list of unique 3-digit even numbers is returned.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?