Created
September 9, 2018 18:46
-
-
Save jianminchen/c27c5c878e0619a0b20eaaf7b5a5c27f to your computer and use it in GitHub Desktop.
902 Numbers at most given digit set - wrote the code in the contest and first few hours after the content
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Solution { | |
public int AtMostNGivenDigitSet(string[] sortedDigits, int N) | |
{ | |
var number = AtMostNGivenDigitSetHelper(sortedDigits, N); | |
return number; | |
} | |
public static int AtMostNGivenDigitSetHelper(string[] sortedDigits, int N) | |
{ | |
if (N <= 0) | |
return 0; | |
var smallerEqualOnes = findLessEqual(sortedDigits); | |
var smallerOnes = findLess(sortedDigits); | |
var hashset = new HashSet<int>(); | |
foreach (var item in sortedDigits) | |
{ | |
hashset.Add((int)(item[0] - '0')); | |
} | |
// base case | |
if (N < 10) | |
{ | |
return smallerEqualOnes[N - 1]; | |
} | |
var count = 0; | |
var chars = N.ToString(); | |
var leftmostDigit = (chars[0] - '0'); | |
var digits = sortedDigits.Length; | |
var length = chars.Length; | |
var numbers = smallerOnes[leftmostDigit - 1]; | |
count += numbers * (int)Math.Pow(digits, length - 1); | |
if (hashset.Contains(leftmostDigit)) | |
{ | |
// 123 - >= 100 and < 123 | |
count += AtMostNGivenDigitSetHelper(sortedDigits, Convert.ToInt32(chars.Substring(1))); | |
} | |
// < 100 | |
for(int i = 0; i < length - 1; i++) | |
{ | |
count += (int)Math.Pow(digits, i + 1); | |
} | |
return count; | |
} | |
private static int[] findLessEqual(string[] D) | |
{ | |
var hashset = new HashSet<int>(); | |
foreach (var item in D) | |
{ | |
hashset.Add((int)(item[0] - '0')); | |
} | |
var numbers = new int[9]; // 0 - 8 | |
int count = 0; | |
for (int i = 1; i <= 9; i++) | |
{ | |
if (hashset.Contains(i)) | |
count++; | |
numbers[i - 1] = count; | |
} | |
return numbers; | |
} | |
// 1 2 3 | |
private static int[] findLess(string[] D) | |
{ | |
var hashset = new HashSet<int>(); | |
foreach (var item in D) | |
{ | |
hashset.Add((int)(item[0] - '0')); | |
} | |
var numbers = new int[9]; // 0 - 8 | |
int count = 0; | |
for (int i = 1; i <= 9; i++) | |
{ | |
if (hashset.Contains(i - 1)) | |
count++; | |
numbers[i - 1] = count; | |
} | |
return numbers; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment