【數論 dw】B053_改變一個整數能得到的最大差值(枚舉 + 剪枝)

一、Problem

You are given an integer num. You will apply the following steps exactly two times:

  • Pick a digit x (0 <= x <= 9).
  • Pick another digit y (0 <= y <= 9). The digit y can be equal to x.
  • Replace all the occurrences of x in the decimal representation of num by y.
    The new integer cannot have any leading zeros, also the new integer cannot be 0.
  • Let a and b be the results of applying the operations to num the first and second times, respectively.

Return the max difference between a and b.

Input: num = 555
Output: 888
Explanation: The first time pick x = 5 and y = 9 and store the new integer in a.
The second time pick x = 5 and y = 1 and store the new integer in b.
We have now a = 999 and b = 111 and max difference = 888

方法一:枚舉

  • 先取出 num 的各個數位到 int[] dig
  • 然後雙重循環分別枚舉 x 和 y
  • 然後枚舉 dig 數組,每次取出一位數位 dig[i] 後,判斷 x 是否等於 dig[i]:
    • 是,則替換爲 y
    • 否則,不作任何操作。
  • 然後,將替換或否的數位變成數字 next
  • 判斷 next 是否合法,用 mi、ma 記錄每一次替換或否後數字的值
  • 最後返回 ma-mi
public int maxDiff(int num) {
    int top = 0, dig[] = new int[10], t = num;
    while (t > 0) {
        dig[top++] = t % 10;
        t /= 10;
    }
    int mi = num, ma = num;
    for (int x = 0; x < 10; x++)
    for (int y = 0; y < 10; y++) {
        int next = 0;
        for (int i = top-1; i >= 0; i--) {
            int cur = dig[i];
            if(cur == x) 
                cur = y;
            next = next * 10 + cur;
        }
        if (next == 0)
            continue;
        mi = Math.min(mi, next);
        ma = Math.max(ma, next);
    }
    return ma - mi;
}

樣例過得很完美,看起來也沒什麼問題,提交一發後,不知不覺地留下 WA 的淚水:看一下,有啥問題,哦,原來是不能有前導 0…

public int maxDiff(int num) {
    int top = 0, dig[] = new int[10], t = num;
    while (t > 0) {
        dig[top++] = t % 10;
        t /= 10;
    }
    int mi = num, ma = num;
    for (int x = 0; x < 10; x++)
    for (int y = 0; y < 10; y++) {
        int next = 0;
        for (int i = top-1; i >= 0; i--) {
            int cur = dig[i];
            if(cur == x) 
                cur = y;
            if (i == top-1 && cur == 0)	//最高位不能爲0
                break;
            next = next * 10 + cur;
        }
        if (next == 0)
            continue;
        mi = Math.min(mi, next);
        ma = Math.max(ma, next);
    }
    return ma - mi;
}

複雜度分析

  • 時間複雜度:O(n)O(n),num 的位數
  • 空間複雜度:O(1)O(1)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章