classSolution { public: intmaxDiff(int num){ auto change = [&](int x, int y) { string num_s = to_string(num); for (char& digit: num_s) { if (digit - '0' == x) { digit = '0' + y; } } return num_s; };
int min_num = num; int max_num = num; for (int x = 0; x < 10; ++x) { for (int y = 0; y < 10; ++y) { string res = change(x, y); // 判断是否有前导零 if (res[0] != '0') { int res_i = stoi(res); min_num = min(min_num, res_i); max_num = max(max_num, res_i); } } }
return max_num - min_num; } };
[sol1-Python3]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
classSolution: defmaxDiff(self, num: int) -> int: defchange(x, y): returnstr(num).replace(str(x), str(y)) min_num = max_num = num for x inrange(10): for y inrange(10): res = change(x, y) # 判断是否有前导零 if res[0] != "0": res_i = int(res) min_num = min(min_num, res_i) max_num = max(max_num, res_i) return max_num - min_num
classSolution { publicintmaxDiff(int num) { intmin_num= num; intmax_num= num; for (intx=0; x < 10; ++x) { for (inty=0; y < 10; ++y) { Stringres= change(num, x, y); // 判断是否有前导零 if (res.charAt(0) != '0') { intres_i= Integer.parseInt(res); min_num = Math.min(min_num, res_i); max_num = Math.max(max_num, res_i); } } }
return max_num - min_num; }
public String change(int num, int x, int y) { StringBuffernum_s=newStringBuffer(String.valueOf(num)); intlength= num_s.length(); for (inti=0; i < length; i++) { chardigit= num_s.charAt(i); if (digit - '0' == x) { num_s.setCharAt(i, (char) ('0' + y)); } } return num_s.toString(); } }
复杂度分析
时间复杂度:O(d^2 \log (\textit{num})),其中 d = 10,表示 num 是一个「十」进制数。我们使用两重循环枚举所有的替换方法,时间复杂度为 O(d^2)。对于每一种替换方法,我们将 num 转换成字符串后并进行替换操作,需要的时间与 num 的长度成正比,记为 O(\log (\textit{num}))。