386.lexicographical-numbers.go 714 B

12345678910111213141516171819202122232425262728293031323334
  1. func lexicalOrder(n int) []int {
  2. res := make([]int, n)
  3. if n == 0 {
  4. return res
  5. }
  6. res[0] = 1
  7. for i := 1; i < n; i++ {
  8. if pre := res[i-1]; pre*10 <= n {
  9. res[i] = pre * 10
  10. } else if pre != n && pre%10 != 9 {
  11. res[i] = pre + 1
  12. } else {
  13. for res[i] = pre / 10; res[i]%10 == 9; res[i] /= 10 {
  14. }
  15. res[i]++
  16. }
  17. }
  18. return res
  19. }
  20. type ints []int
  21. func (is ints) Len() int { return len(is) }
  22. func (is ints) Less(i, j int) bool { return strconv.Itoa(is[i]) < strconv.Itoa(is[j]) }
  23. func (is ints) Swap(i, j int) { is[i], is[j] = is[j], is[i] }
  24. func lexicalOrderSort(n int) []int {
  25. res := make([]int, n)
  26. for i := 0; i < n; i++ {
  27. res[i] = i + 1
  28. }
  29. sort.Sort(ints(res))
  30. return res
  31. }