Monday, August 31, 2015

Kth Smallest Element in a BST

Given a binary search tree, write a function kthSmallest to find the kth smallest element in it.
Note: 
You may assume k is always valid, 1 ≤ k ≤ BST's total elements.
class Solution {
public:
    void pushLefts(stack<TreeNode*>& s, TreeNode* root)
    {
        while(root != NULL)
        {
            s.push(root);
            root = root->left;
        }
    }
    int kthSmallest(TreeNode* root, int k) {
        stack<TreeNode*> tmp;
        pushLefts(tmp, root);
        while (!tmp.empty())
        {
            TreeNode* cur = tmp.top();
            tmp.pop();
            if (k == 1)
            {
                return cur->val;
            }
            pushLefts(tmp, cur->right);
            k--;
        }
        return -1;
    }
};

Saturday, August 29, 2015

Longest Consecutive Sequence


Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
For example,
Given [100, 4, 200, 1, 3, 2],
The longest consecutive elements sequence is [1, 2, 3, 4]. Return its length: 4.
Your algorithm should run in O(n) complexity.
Runtime: 36 ms

int longestConsecutive(vector<int>& nums) {
        unordered_map<int, int> tmp;
        int maxN = 0;
        for (int i = 0; i != nums.size(); ++i)
        {
            int t = nums[i];
            if (tmp.find(t) != tmp.end())
            {
                continue;
            }
            else
            {
                tmp[t] = t;
                maxN = max(maxN, 1);
            }
            if (tmp.find(t - 1) != tmp.end() && tmp[t-1] < t)
            {
                maxN = max(maxN, t - tmp[t-1] + 1);
                tmp[t] = tmp[t - 1];
                tmp[tmp[t-1]] = t;
            }
            if (tmp.find(t + 1) != tmp.end() && tmp[t+1] > t)
            {
                maxN = max(maxN, tmp[t+1] - tmp[t] + 1);
                int lowerBound = tmp[t];
                tmp[lowerBound] = tmp[t+1];
                tmp[tmp[t+1]] = lowerBound;
            }
        }
        return maxN;
    }