1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
| func nextGreaterElement(n int) int { nums := toArr(n) length := len(nums) for i := len(nums) - 2; i >= 0; i-- { if nums[i] < nums[i + 1] { sort.Ints(nums[i + 1:]) for j := i + 1; j < length; j++ { if nums[i] < nums[j] { nums[i], nums[j] = nums[j], nums[i] break } } maxMinNum := toNum(nums) if maxMinNum <= math.MaxInt32 { return maxMinNum } break } } return -1 }
func toArr(n int) []int { arr := []int{} for n != 0 { arr = append(arr, n % 10) n /= 10 } for i, j := 0, len(arr) - 1; i < j; i, j = i + 1, j - 1 { arr[i], arr[j] = arr[j], arr[i] } return arr }
func toNum(nums []int) int { num := 0 for i := 0; i < len(nums); i++ { num = num * 10 + nums[i] } return num }
|