Anyway to improve the efficiency?


  • 0
    F

    I though my code is already O(n), but there are over 60% of code run faster than mine. So is there any way to improve the code?

    char* convert(char* s, int numRows)
    {
            if(numRows == 1 || numRows >= strlen(s)) return s;
            int distance = (numRows-1)*2, i = 0, len = strlen(s), index = i;
            char *result = (char *)malloc(sizeof(char)*(len+1));
            while(j < len)
            {
                    if((i == 0) || (i == numRows-1))
                    {
                            result[j++] = s[index];
                            index = index + distance;
                    }
                    else
                    {
                            result[j++] = s[index];
                            index = index + distance - 2*i;
                            if(index < len)
                            {
                                    result[j++] = s[index];
                                    index = index + 2*i;
                            }
                    }
                    if(index >= len)  index = ++i;
            }
            result[len] = '\0';
            return result;
    }

  • 0
    J

    remove malloc, use global char* array variable, will enhance 3ms.


Log in to reply
 

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