668.kth-smallest-number-in-multiplication-table.go 532 B

12345678910111213141516171819202122232425262728293031
  1. func findKthNumber(m int, n int, k int) int {
  2. beg, end := 1, m*n
  3. for beg <= end {
  4. mid := beg + (end-beg)/2
  5. if rank(m, n, mid) < k {
  6. beg = mid + 1
  7. } else {
  8. end = mid - 1
  9. }
  10. }
  11. return beg
  12. }
  13. func rank(m, n, x int) (cnt int) {
  14. // Find the rank row by row.
  15. // Assume that x is in the ith row:
  16. // 1*i 2*i 3*i ... n*i, then
  17. // x/i is in row 1 2 3 ... n,
  18. // so x is the (x/i)th num.
  19. for i := 1; i <= m; i++ {
  20. cnt += minInt(n, x/i)
  21. }
  22. return cnt
  23. }
  24. func minInt(x, y int) int {
  25. if x < y {
  26. return x
  27. }
  28. return y
  29. }