LeetCode 273. Integer to English Words 的时间复杂度是多少?

What is the Time Complexity of LeetCode 273. Integer to English Words?

我很难理解这个解决方案的时间复杂度。这道题是关于将数字转换为英文单词的问题。

例如, 输入:num = 1234567891 输出:“12345567891”

StringBuilder insert() 的时间复杂度为 O(n)。
我怀疑时间复杂度是 O(n^2)。但我不确定。其中 n 是位数。 Link 提问:englishToWords

有我的代码:

代码:

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);
        }
    }
}

它是 O(log n),假设 nnum,因为你得到的更少n的数值每位数不超过2个字,位数为ceil(log₁₀(n)).

将价值翻倍可能会增加 2 个单词,仅此而已。

时间复杂度为 O(n),其中 n 是给定数字的位数。 我们正在遍历一次数字。

我从在 Cisco 和 Google 工作的几个朋友那里证实了这一点。