-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Given two integers n and k, return the kth lexicographically smallest integer in the range [1, n]. Example 1: Input: n = 13, k = 2 Output: 10 Explanation: The lexicographical order is [1, 10, 11, 12, 13, 2, 3, 4, 5, 6, 7, 8, 9], so the second smallest number is 10. Example 2: Input: n = 1, k = 1 Output: 1 Constraints: 1 <= k <= n <= 109
- Loading branch information
1 parent
e4c440c
commit b013f7b
Showing
2 changed files
with
77 additions
and
0 deletions.
There are no files selected for viewing
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,29 @@ | ||
package _440 | ||
|
||
func findKthNumber(n int, k int) int { | ||
current := 1 | ||
k -= 1 // ponieważ zaczynamy od pierwszej liczby | ||
|
||
for k > 0 { | ||
steps := calculateSteps(current, current+1, n) | ||
if steps <= k { | ||
current += 1 | ||
k -= steps | ||
} else { | ||
current *= 10 | ||
k -= 1 | ||
} | ||
} | ||
|
||
return current | ||
} | ||
|
||
func calculateSteps(curr, next, n int) int { | ||
steps := 0 | ||
for curr <= n { | ||
steps += min(n+1, next) - curr | ||
curr *= 10 | ||
next *= 10 | ||
} | ||
return steps | ||
} |
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,48 @@ | ||
package _440 | ||
|
||
import ( | ||
"testing" | ||
) | ||
|
||
func Test_findKthNumber(t *testing.T) { | ||
type args struct { | ||
n int | ||
k int | ||
} | ||
tests := []struct { | ||
name string | ||
args args | ||
want int | ||
}{ | ||
{ | ||
name: "Example 1", | ||
args: args{ | ||
n: 13, | ||
k: 2, | ||
}, | ||
want: 10, | ||
}, | ||
{ | ||
name: "Example 2", | ||
args: args{ | ||
n: 10, | ||
k: 3, | ||
}, | ||
want: 2, | ||
}, | ||
} | ||
|
||
for _, tt := range tests { | ||
t.Run(tt.name, func(t *testing.T) { | ||
if got := findKthNumber(tt.args.n, tt.args.k); got != tt.want { | ||
t.Errorf("findKthNumber() = %v, want %v", got, tt.want) | ||
} | ||
}) | ||
} | ||
} | ||
|
||
func BenchmarkFindKthNumber(b *testing.B) { | ||
for i := 0; i < b.N; i++ { | ||
findKthNumber(4089173, 3098723) | ||
} | ||
} |