LeetCode Week 2

IfThenElse-Meituan發表於2017-04-08

LeetCode Week 2

保護好你的身體,和病痛比起來,其他的困難都不值一提

問題集合

1. Invert Binary Tree(Easy 226)

Invert a binary tree.

     4
   /   \
  2     7
 / \   / \
1   3 6   9

to

     4
   /   \
  7     2
 / \   / \
9   6 3   1

Trivia:
This problem was inspired by this original tweet by Max Howell:

Google: 90% of our engineers use the software you wrote (Homebrew), but you can’t invert a binary tree on a whiteboard so fuck off

Solution:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */
struct TreeNode* invertTree(struct TreeNode* root) {
    recursiveInvertTree(root);
    return root;
}

void recursiveInvertTree(struct TreeNode* root) {
    if (!root) return;
    struct TreeNode *tmp = root->right;
    root->right = root->left;
    root->left = tmp;
    recursiveInvertTree(root->left);
    recursiveInvertTree(root->right);
}

2.Single Number (Easy 136)

Given an array of integers, every element appears twice except for one. Find that single one.

Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
Solution:

int singleNumber(int* nums, int numsSize) {
    int result = 0;
    for (int i = 0; i < numsSize; i ++) {
        result ^= nums[i];
    }

    return result;
}

3.Find the Difference (Easy 389)

Given two strings s and t which consist of only lowercase letters.

String t is generated by random shuffling string s and then add one more letter at a random position.

Find the letter that was added in t.

Example:

Input:
s = "abcd"
t = "abcde"

Output:
e

Explanation:
'e' is the letter that was added.

Solution:

char findTheDifference(char* s, char* t) {
    int container[26];
    for (int i = 0; i < 26; i++) {
        container[i] = 0;
    }

    for (int i = 0; i < strlen(s); i++) {
        container[s[i] - 'a']--;
    }

    for (int j = 0; j < strlen(t); j++) {
        container[t[j] - 'a']++;
    }

    for (int i = 0; i < 26; i++) {
        if (container[i] > 0) return i + 'a';
    }
    return 0;
}

4. Odd Even Linked List (Medium 328)

Given a singly linked list, group all odd nodes together followed by the even nodes. Please note here we are talking about the node number and not the value in the nodes.

You should try to do it in place. The program should run in O(1) space complexity and O(nodes) time complexity.

Example:

Given 1->2->3->4->5->NULL,
return 1->3->5->2->4->NULL.

Note:
The relative order inside both the even and odd groups should remain as it was in the input.
The first node is considered odd, the second node even and so on …

Solution:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* oddEvenList(struct ListNode* head) {
    struct ListNode* oddHead, *evenHead, *oddP, *evenP, *tmp;
    oddHead = evenHead = oddP = evenP = tmp = NULL;
    int counter = 1;

    while(head) {
        tmp = head;
        head = head->next;
        // odd node
        if (counter++ % 2 == 1) {
            if (!oddHead) {
                oddHead = oddP = tmp;
            }
            else {
                oddP->next = tmp;
                oddP = tmp;
            }
            oddP->next = NULL;
        }
        // even node
        else {            
            if (!evenHead) {
                evenHead = evenP = tmp;
            }
            else {
                evenP->next = tmp;
                evenP = tmp;
            }
            evenP->next = NULL;
        }
    }

    if (oddP) {
        oddP->next = evenHead;
    }

    return oddHead;
}

5.Minimum Time Difference (Medium 539)

Given a list of 24-hour clock time points in “Hour:Minutes” format, find the minimum minutes difference between any two time points in the list.

Example 1:

Input: ["23:59","00:00"]
Output: 1

Note:
1.The number of time points in the given list is at least 2 and won’t exceed 20000.
2.The input time is legal and ranges from 00:00 to 23:59.

Solution:

int findMinDifference(char** timePoints, int timePointsSize) {
    int size = 24 * 60;
    int *values = (int *)malloc(sizeof(int) * size);
    for (int i = 0; i < size; i++) {
        values[i] = 0;
    }

    for (int i = 0; i < timePointsSize; i++) {
        values[toMinutesValue(timePoints[i])] ++;
    }

    int result, min, max, last;
    result = min = size;
    max = last = -1;

    for (int i = 0; i < size; i++) {
        if (values[i] == 0) continue;
        if (values[i] >= 2) return 0;

        if (min > i) {
            min = i;
        }
        if (max < i) {
            max = i;
        }
        if (last == -1) {
            last = i;
            continue;
        }

        if (result > (i - last)) {
            result = i - last;
        }

        last = i;
    }

    if (result > (min + size - max)) {
        result = min + size - max;
    }

    return result;
}

int toMinutesValue(char* str) {
    return ((str[0] - '0') * 10 + (str[1] - '0')) * 60 + (str[3] - '0') * 10 + (str[4] - '0');
}

6.Binary Tree Inorder Traversal (Medium 94)

Given a binary tree, return the inorder traversal of its nodes’ values.

For example:
Given binary tree [1,null,2,3],

   1
    \
     2
    /
   3

return [1,3,2].
Note: Recursive solution is trivial, could you do it iteratively?

Solution:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<int> inorderTraversal(TreeNode* root) {
        vector<int> result;
        stack<TreeNode*> nStack;
        TreeNode* p = root;

        while(p || !nStack.empty()) {
            if (p) {
                nStack.push(p);
                p = p->left;
            }
            else {
                p = nStack.top();
                nStack.pop();
                result.push_back(p->val);
                p = p->right;
            }
        }

        return result;
    }
};

7.Is Subsequence (Medium 392)

Given a string s and a string t, check if s is subsequence of t.

You may assume that there is only lower case English letters in both s and t. t is potentially a very long (length ~= 500,000) string, and s is a short string (<=100).

A subsequence of a string is a new string which is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, “ace” is a subsequence of “abcde” while “aec” is not).

Example 1:

s = "abc", t = "ahbgdc"
Return true.

Example 2:

s = "axc", t = "ahbgdc"
Return false.

Solution:

bool isSubsequence(char* s, char* t) {
    int index = 0;
    int length = strlen(t);
    for (int i = 0; i < length; i++) {
        if (!s[index]) break;
        if (t[i] == s[index]) {
            index ++;
        }
    }

    return s[index] == 0;
}   

相關文章