超过时间限制Leetcode

时间:2019-11-10 23:51:31

标签: java

我试图使用以下代码来判断整数是否是回文

public boolean isPalindrome(int num){
   if(num < 0) return  false; 
   int reversed = 0, remainder, original = num;
   while(num != 0) {
        remainder = num % 10; // reversed integer is stored in variable
        reversed = reversed * 10 + remainder; //multiply reversed by 10 then add the remainder so it 
gets stored at next decimal place.
        num  /= 10;  //the last digit is removed from num after division by 10.
    }
    // palindrome if original and reversed are equal
    return original == reversed;
}

此算法的运行时复杂度为$ O(n)$,因为您必须执行num%10 n次。但是,这超出了时间限制。

相反,以下算法有效

public class Solution {
    public boolean isPalindrome(int x) {
        // Special cases:
        // As discussed above, when x < 0, x is not a palindrome.
        // Also if the last digit of the number is 0, in order to be a palindrome,
        // the first digit of the number also needs to be 0.
        // Only 0 satisfy this property.
        if(x < 0 || (x % 10 == 0 && x != 0)) {
            return false;
        }

        int revertedNumber = 0;
        while(x > revertedNumber) {
            revertedNumber = revertedNumber * 10 + x % 10;
            x /= 10;
        }

        // When the length is an odd number, we can get rid of the middle digit by revertedNumber/10
        // For example when the input is 12321, at the end of the while loop we get x = 12, revertedNumber = 123,
       // since the middle digit doesn't matter in palidrome(it will always equal to itself), we can 
simply get rid of it.
       return x == revertedNumber || x == revertedNumber/10;
    }
}

它的运行时复杂度是否仍为O(n)?

0 个答案:

没有答案