题目:给定两个数组表示的整数,比如x = 1234={1,2,3,4},y=2410={2,4,1,0},返回第一个整数的重组后的值最接近第二个整数,并且要大于第二个整数。假设两个整数的数组大小相同,并且肯定能够找到符合答案的数,例如输入{1,2,3,4},{2,4,1,0},返回{2,4,1,3}。
package main import ( "fmt" ) func getCloseBigger(x, y []int) ([]int, bool) { xlen, ylen := len(x), len(y) if xlen != ylen || xlen == 0 { return nil, false } res, ys := make([]int, 0), make([]int, 10) for i := 0; i < xlen; i += 1 { ys[y[i]] += 1 } for i := 0; i < xlen; i += 1 { if ys[x[i]] != 0 { res = append(res, x[i]) ys[x[i]] -= 1 } else { // 不同则遍历ys中有没有比x[i]更大的值 flag := false for j := i; j < 10; j += 1 { if ys[j] != 0 { flag = true res = append(res, j) ys[j] -= 1 } if flag { for k := 0; k < 10; k += 1 { if ys[k] != 0 { res = append(res, k) ys[k] -= 1 } } return res, true } } return res, false } } return res, true } func main() { res, b := getCloseBigger([]int{3, 2, 1, 4}, []int{2, 3, 4, 1}) fmt.Println(res, b) }