leetcode 273的时间复杂度是多少整数到英文单词?

0yycz8jy  于 2021-06-29  发布在  Java
关注(0)|答案(2)|浏览(481)

我正在努力理解这个解决方案的时间复杂性。这个问题是关于把数字转换成英语单词的。
例如,input:num=1234567891 output:“一亿二亿三千四百五十六万七千八百九十一”
stringbuilder insert()的时间复杂度为o(n)。
我怀疑时间复杂度是o(n^2)。但我不确定。其中n是位数。问题链接:英语单词
这是我的密码:
代码:

class Solution {
    private final String[] THOUSANDS = {"", "Thousand", "Million", "Billion"};

    private final String[] LESS_THAN_TWENTY = {"", "One", "Two", "Three", "Four", "Five", 
    "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen",
     "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"};

    private final String[] TENS = {"", "", "Twenty", "Thirty", "Forty", "Fifty",
     "Sixty", "Seventy", "Eighty", "Ninety"};
    //O(n) solution
    public String numberToWords(int num) {
        if (num == 0){
          return "Zero";  
        } 
        StringBuilder sb = new StringBuilder();
        int index = 0;
        //this contributes towards time complexity
        while (num > 0) {
            if (num % 1000 > 0) {
                StringBuilder tmp = new StringBuilder();
                helper(tmp, num % 1000);
                System.out.println(index);
                System.out.println("tmp: "+ tmp);
                tmp.append(THOUSANDS[index]).append(" ");
                //I suspect the time complexity will increase because of this to O(n^2)
                sb.insert(0, tmp);
            }
            index++;
            num = num / 1000;
        }
        return sb.toString().trim();
    }

    private void helper(StringBuilder tmp, int num) {
        if (num == 0) {
            return;
        } else if (num < 20) {
            tmp.append(LESS_THAN_TWENTY[num]).append(" ");
            return;
        } else if (num < 100) {
            tmp.append(TENS[num / 10]).append(" ");
            helper(tmp, num % 10);
        } else {
            tmp.append(LESS_THAN_TWENTY[num / 100]).append(" Hundred ");
            helper(tmp, num % 100);
        }
    }
}
sz81bmfz

sz81bmfz1#

时间复杂度为o(n),其中n是给定数字中的位数。我们只遍历一次数字。
我从思科和谷歌的几个朋友那里证实了这一点。

ffx8fchx

ffx8fchx2#

假设是o(对数n) nnum ,因为的数值的每位数少于2个字 n ,位数为 ceil(log₁₀(n)) .
加倍的价值可能会增加两个字,就是这样。

相关问题