788. Rotated Digits

Description

X is a good number if after rotating each digit individually by 180 degrees, we get a valid number that is different from X. Each digit must be rotated - we cannot choose to leave it alone.

A number is valid if each digit remains a digit after rotation. 0, 1, and 8 rotate to themselves; 2 and 5 rotate to each other; 6 and 9 rotate to each other, and the rest of the numbers do not rotate to any other number and become invalid.

Now given a positive number N, how many numbers X from 1 to N are good?

Example:
Input: 10
Output: 4
Explanation:
There are four good numbers in the range [1, 10] : 2, 5, 6, 9.
Note that 1 and 10 are not good numbers, since they remain unchanged after rotating.

Note:

  • N will be in range [1, 10000].

Solution

Brute-force, O(n logn), S(1)

isGood()的时间复杂度是log n?感觉很怪,应该是O(1)啊。。

class Solution {
    public int rotatedDigits(int N) {
        int count = 0;
        for (int i = 1; i <= N; ++i) {
            if (isGood(i)) {
                ++count;
            }
        }
        
        return count;
    }
    
    private boolean isGood(int n) {
        boolean isRotated = false;
        
        while (n > 0) {
            int d = n % 10;
            
            if (d == 2 || d == 5 || d == 6 || d == 9) {
                isRotated = true;
            } else if (d == 3 || d == 4 || d == 7) {
                break; 
            }
            
            n /= 10;
        }
        
        return n <= 0 && isRotated;
    }
}

DP, O(n), S(n)

class Solution {
    public int rotatedDigits(int N) {
        // dp[i] = 0: invalid, 1: valid without rotate,
        // 2: valid with rotate
        int[] dp = new int[N + 1];
        int count = 0;  // store the count of dp[i] == 2
        
        for (int i = 0; i <= N; ++i) {
            if (i < 10) {
                if (i == 0 || i == 1 || i == 8) {
                    dp[i] = 1;
                } else if (i == 2 || i == 5 || i == 6 || i == 9) {
                    dp[i] = 2;
                    ++count;
                }
            } else {
                int a = i / 10;
                int b = i % 10;
                
                if (dp[a] == 1 && dp[b] == 1) {
                    dp[i] = 1;
                } else if (dp[a] > 0 && dp[b] > 0) {
                    dp[i] = 2;
                    ++count;
                }
            }
        }
        
        return count;
    }
}

Generate numbers using DP, O(log n), S(1)

leetcode提供的解法,还没看懂。

你可能感兴趣的:(788. Rotated Digits)