package main import ( "fmt" "sort""strconv") funcfindMaxLessThanN(target int, nums []int) (result int) { targetStr := strconv.Itoa(target) var targetNums []int for i, _ := range targetStr { targetNums = append(targetNums, int(targetStr[i]-'0')) } // Sort A in descending order sort.Sort(sort.Reverse(sort.IntSlice(nums))) ASet := make(map[int]bool) for _, a := range nums { ASet[a] = true } length := len(targetNums) for i := 0; i < length; i++ { currentDigit := targetNums[i] largestLess, found := findLargestLessThan(currentDigit, nums) if found { // Replace the current digit with the largest less than itself targetNums[i] = largestLess // Fill the rest of the digits with the largest in A for j := i + 1; j < length; j++ { targetNums[j] = nums[0] } break } elseif !ASet[currentDigit] { // If current digit is not in A and we cannot find a smaller digit, backtrack for i >= 0 && !ASet[targetNums[i]] { i-- } if i < 0 { // If no valid digit was found, return the largest possible number with one less digit result := 0 for j := 0; j < length-1; j++ { result = result*10 + nums[0] } return result } // Replace the found digit with the largest less than itself and fill the rest largestLess, _ = findLargestLessThan(targetNums[i], nums) targetNums[i] = largestLess for j := i + 1; j < length; j++ { targetNums[j] = nums[0] } break } } // Convert the runes back to an integer for _, n := range targetNums { result = result*10 + n } return result } // findLargestLessThan finds the largest digit in A that is less than the given digitfunc findLargestLessThan(digit int, A []int) (int, bool) { for _, a := range A { if a < digit { return a, true } } return0, false } funcmain() { n := 23121 A := []int{2, 4, 9} fmt.Println(findMaxLessThanN(n, A)) // Output: 22999 }
详细解释
findLargestLessThan: 一个辅助函数,用于找到集合 A 中小于给定数字的最大数字。
findMaxLessThanN: 主要函数,根据给定数字 n 和集合 A,逐位处理,找到满足条件的最大数字。