LeetCode Week 1

IfThenElse-Meituan發表於2017-04-01

LeetCode Week 1

Time You Enjoy Wasting, is Not Wasted Time

問題集合

1. Fizz Buzz (Easy 412)

Write a program that outputs the string representation of numbers from 1 to n.

But for multiples of three it should output “Fizz” instead of the number and for the multiples of five output “Buzz”. For numbers which are multiples of both three and five output “FizzBuzz”.
Example:

n = 15,

Return:
[
    "1",
    "2",
    "Fizz",
    "4",
    "Buzz",
    "Fizz",
    "7",
    "8",
    "Fizz",
    "Buzz",
    "11",
    "Fizz",
    "13",
    "14",
    "FizzBuzz"
]

Solution:

/**
 * Return an array of size *returnSize.
 * Note: The returned array must be malloced, assume caller calls free().
 */
char** fizzBuzz(int n, int* returnSize) {
    char **result = NULL;
    (*returnSize) = 0;
    if (n <= 0) return result;

    // the max string size with \0 
    int numLen = 1;
    for(int i = n; i > 0; numLen++, i /= 10);
    numLen = numLen > 9 ? numLen : 9;

    result = (char **)malloc(sizeof(char *) * n);
    for (int i = 0; i < n; i++) {
        result[i] = (char *)malloc(sizeof(char) * numLen);

        int num = i + 1;
        if (num % 3 == 0 && num % 5 == 0) {
            strcpy(result[i], "FizzBuzz");
        }
        else if (num % 3 == 0) {
            strcpy(result[i], "Fizz");
        }
        else if (num % 5 == 0) {
            strcpy(result[i], "Buzz");
        }
        else {
            int index = 0;
            while (num) {
                result[i][index++] = '0' + num % 10;
                num /= 10;
            }

            // reverse the string
            for (int x = 0, y = index - 1; x < y; x++, y--) {
                char tmp = result[i][x];
                result[i][x] = result[i][y];
                result[i][y] = tmp;
            }
            result[i][index] = '\0';
        }
    }

    (*returnSize) = n;
    return result;

2.Reverse String (Easy 344)

Write a function that takes a string as input and returns the string reversed.
Example:

Given s = "hello", return "olleh".

Solution:

char* reverseString(char* s) {
    if (!s) return NULL;
    for (int i = 0, j = strlen(s) - 1; i < j; i++, j--) {
        char tmp = s[i];
        s[i] = s[j];
        s[j] = tmp;
    }

    return s;
}

3.Next Greater Element I (Easy 496)

You are given two arrays (without duplicates) nums1 and nums2 where nums1’s elements are subset of nums2. Find all the next greater numbers for nums1’s elements in the corresponding places of nums2.

The Next Greater Number of a number x in nums1 is the first greater number to its right in nums2. If it does not exist, output -1 for this number.
Example 1:

Input: nums1 = [4,1,2], nums2 = [1,3,4,2].
Output: [-1,3,-1]
Explanation:
    For number 4 in the first array, you cannot find the next greater number for it in the second array, so output -1.
    For number 1 in the first array, the next greater number for it in the second array is 3.
    For number 2 in the first array, there is no next greater number for it in the second array, so output -1.

Example 2:

Input: nums1 = [2,4], nums2 = [1,2,3,4].
Output: [3,-1]
Explanation:
    For number 2 in the first array, the next greater number for it in the second array is 3.
    For number 4 in the first array, there is no next greater number for it in the second array, so output -1.

Note :
1.All elements in nums1 and nums2 are unique.
2.The length of both nums1 and nums2 would not exceed 1000.

Solution:

/**
 * Return an array of size *returnSize.
 * Note: The returned array must be malloced, assume caller calls free().
 */
int* nextGreaterElement(int* findNums, int findNumsSize, int* nums, int numsSize, int* returnSize) {
    *returnSize = findNumsSize;
    int* result = (int *)malloc(sizeof(int) * (*returnSize));

    // process with violence --
    for (int i = 0; i < findNumsSize; i++) {
        int pos = -1;
        int value = 0;
        int greater = -1;
        for (int j = 0; j < numsSize; j ++) {
            if (pos == -1 && findNums[i] == nums[j]) {
                pos = j;
                value = nums[j];
            }

            if (pos != -1) {
                if (nums[j] > value) {
                    greater = nums[j];
                    break;
                }
            }
        }
        result[i] = greater;
    }
    return result;
}

4.String to Integer (atoi) (Medium 8)

Implement atoi to convert a string to an integer.

Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases.

Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front.

Solution:

int myAtoi(char* str) {
    int result = 0, sig = 1, index = 0;

    if (!str) return result;
    int size = strlen(str);
    if (size == 0) return result;

    while (index < size)  {
        if (str[index] == ' ') {
            index ++;
            continue;
        }
        else break;
    }
    if (index == size) return result;

    if (str[index] == '+' || str[index] == '-') {
        if (str[index] == '-') sig = -1;
        index ++;
    }

    for (int i = index; i < size; i ++) {
        int num = str[i] - '0';
        // 非法字元
        if (num >= 10 || num < 0) break;
        // 數字越界
        if ((sig == 1) && ((result >= 214748365) || (result == 214748364 && num > 7))) return 2147483647;
        if ((sig == -1) && ((result >= 214748365) || (result == 214748364 && num > 8))) return -2147483648;
        result = result * 10 + num;
    }

    return result * sig;
}

5.Longest Palindromic Substring (Medium 5)

Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
Example 1:

Input: "babad"

Output: "bab"

Note: "aba" is also a valid answer.

Example 2:

Input: "cbbd"

Output: "bb"

Solution:

char* longestPalindrome(char* s) {
    int size = strlen(s);
    int x, y;
    int max = 0;
    int max_x, max_y;
    for (int i = 0; i < size; i ++) {
        // indent = 0 元素i為中心元素
        // indent = 1 元素 i i+1 為對稱中心元素
        for (int indent = 0; indent < 2; indent ++) {
            x = i;
            y = i + indent;
            while ((x >= 0) && (y < size) && (s[x] == s[y])) {
                x --;
                y ++;
            }
            if ( ((y - 1) - (x + 1) + 1) > max) {
                max_x = x + 1;
                max_y = y - 1;
                max = max_y - max_x + 1;
            }
        }
    }

    // TT
    char* result = (char *) malloc(sizeof(char) * (max_y - max_x + 2));
    for (int i = 0; i < max_y - max_x + 1; i ++) result[i] = s[i + max_x];
    result[max_y - max_x + 1] = '\0';
    return result;
}

6.Add Two Numbers (Medium 2)

You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Example :

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8

Solution:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
    struct ListNode* result = NULL;
    struct ListNode* p = NULL;
    int add = 0;
    while(l1 || l2) {
        int x, y;
        x = y = 0;
        if (l1) {
            x = l1->val;
            l1 = l1->next;
        }
        if (l2) {
            y = l2->val;
            l2 = l2->next;
        }

        int sum = add + x + y;
        add = 0;
        if (sum >= 10) {
            sum -= 10;
            add = 1;
        }
        struct ListNode* tmp = (struct ListNode*) malloc(sizeof(struct ListNode));
        if (!tmp) return NULL;

        tmp->val = sum;
        tmp->next = NULL;
        if (p) {
            p->next = tmp;
        }
        else {
            result = tmp;
        }
        p = tmp;
    }

    if (add != 0) {
        struct ListNode* tmp = (struct ListNode*) malloc(sizeof(struct ListNode));
        if (!tmp) return NULL;

        tmp->val = 1;
        tmp->next = NULL;
        p->next = tmp;
    }

    return result;
}

7.Find All Duplicates in an Array (Medium 442)

Given an array of integers, 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.

Find all the elements that appear twice in this array.

Could you do it without extra space and in O(n) runtime?
Example :
Input:
[4,3,2,7,8,2,3,1]

Output:
[2,3]

`Solution:`
```c
/**
 * Return an array of size *returnSize.
 * Note: The returned array must be malloced, assume caller calls free().
 */
int* findDuplicates(int* nums, int numsSize, int* returnSize) {
    *returnSize = 0;
    int *result = NULL;

    result = (int *)malloc(sizeof(int) * numsSize);
    for (int i = 0; i < numsSize; i++) {
        int index = (nums[i] > 0 ? nums[i] : nums[i] * -1) - 1;
        if (nums[index] > 0) {
            nums[index] *= -1;
        }
        else {
            result[(*returnSize)++] = index + 1;
        }
    }
    return result;
}

相關文章