Approach
Sorting and greedy selection
For Unique 3-Digit Even Numbers, the implementation first exposes a useful order, then scans that order while making locally justified choices.
- Choose the key that reveals the greedy or grouping structure.
- Sort the relevant records by that key.
- Scan in order, maintaining the invariant that makes each local choice safe.
Code notes
- 56 lines of Java from the credited upstream file 3483.java.
- The implementation visibly relies on sequence storage, hash lookup, ordered lookup.
- 4 loop blocks detected.
Complexity
Sorting is typically the dominant term unless the subsequent scan uses a more expensive nested operation.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public int totalNumbers(int[] digits) {3 Set<Integer> nums = new HashSet<>();4 int[] perm = digits.clone();5 6 Arrays.sort(perm);7 8 do {9 final int a = perm[0];10 final int b = perm[1];11 final int c = perm[2];12 if (a != 0 && c % 2 == 0) {13 nums.add(a * 100 + b * 10 + c);14 }15 } while (nextPermutation(perm));16 17 return nums.size();18 }19 20 private boolean nextPermutation(int[] nums) {21 final int n = nums.length;22 23 24 int i;25 for (i = n - 2; i >= 0; --i)26 if (nums[i] < nums[i + 1])27 break;28 29 if (i < 0)30 return false;31 32 33 34 for (int j = n - 1; j > i; --j)35 if (nums[j] > nums[i]) {36 swap(nums, i, j);37 break;38 }39 40 41 reverse(nums, i + 1, n - 1);42 return true;43 }44 45 private void reverse(int[] nums, int l, int r) {46 while (l < r)47 swap(nums, l++, r--);48 }49 50 private void swap(int[] nums, int i, int j) {51 final int temp = nums[i];52 nums[i] = nums[j];53 nums[j] = temp;54 }55}56