Memory Limit Exceeded, Why?


  • 0
    G

    class Solution {
    public:
    string convert(string s, int numRows) {
    if (s.empty() || numRows < 1)
    return string("");

        string result("");
        int i, j;
        for (i = 1; i <= numRows; ++i) {
            int idx1 = i;
            int idx2 = 2 * numRows - i;
            for (; idx2 <= s.length(); ) {
                if (idx1 < idx2) {
                    result += s[idx1 - 1];
                    idx1 += 2 * numRows - 2;
                }
                else if (idx1 > idx2) {
                    result += s[idx2 - 1];
                    idx2 += 2 * numRows - 2; 
                }
                else {
                    result += s[idx1 - 1];
                    idx1 += 2 * numRows - 2;
                    idx2 += 2 * numRows - 2;
                }
            }
        }
        return result;
    }
    

    };


  • 0
    B

    The time complexity of your answer is $O(n^2)$, while this problem need a $O(n)$ solution.


  • 0
    G

    Thank you very much. But I think the time complexity of this algorithm is O(n), although there are two loops. Also, it prompted "Memory Limit Exceeded", and not "Time Limit Exceeded".


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.