【LeetCode】Algorithms 題集(八)

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.


    Follow up:

    What if the BST is modified (insert/delete operations) often and you need to find the kth smallest frequently? How would you optimize the kthSmallest routine?

    Hint:

    Try to utilize the property of a BST.

    What if you could modify the BST node's structure?

    The optimal runtime complexity is O(height of BST).

思路:

    在一個 BST 中找第 k 小的數,而且利用 BST 的性質來做。找第 k 小什麼時候最方便呢?如果數組是有序的那遍歷到第 k 個就好了。

    BST 可不可以變成一個有序的數組呢?或者說,什麼時候我們會從 BST 中得到一組有序的數呢?由 BST 左子樹的值都小於根節點,右子樹的值都大於根節點。所以中序遍歷的時候得到的就是有序數組。那麼,只要中序遍歷到第 k 個輸出就好了。

代碼:

/**
 * 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:
    int kthSmallest(TreeNode* root, int k) {
        int cur = 0;
        
        /* 非遞歸中序遍歷 */
        stack<TreeNode*> s;
        TreeNode* p = root;
        while(p != NULL || !s.empty()) {
            while(p != NULL) {
                s.push(p);
                p = p->left;
            }
            
            if(!s.empty()) {
                p = s.top();
                s.pop();
                cur++;
                /* 第 K 個 */
                if(cur == k) return p->val;
                p = p->right;
            }
        }
    }
    
    
};

Delete Node in a Linked List 

題意:

    Write a function to delete a node (except the tail) in a singly linked list, given only access to that node.

    Supposed the linked list is 1 -> 2 -> 3 -> 4 and you are given the third node with value 3, the linked list should become 1 -> 2 -> 4 after calling your function.

思路:

    刪除給定的節點。用下個節點的值代替當前節點,並釋放下個節點空間。

代碼:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    void deleteNode(ListNode* node) {
        ListNode* next = node->next;
        *(node) = *(node->next);
        delete next;
    }
};


Lowest Common Ancestor of a Binary Search Tree

題意:

Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST.

According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes v and w as the lowest node in T that has both v and w as descendants (where we allow a node to be a descendant of itself).”

        _______6______
       /              \
    ___2__          ___8__
   /      \        /      \
   0      _4       7       9
         /  \
         3   5

For example, the lowest common ancestor (LCA) of nodes 2 and 8 is 6. Another example is LCA of nodes 2 and 4 is 2, since a node can be a descendant of itself according to the LCA definition.


思路:

    在二叉搜索樹上尋找兩個節點的最近公共祖先。利用二叉搜索樹的性質,用 p 和 q 的值與根節點的比較結果決定最近公共祖先的位置。


代碼:

/**
 * 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:
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        TreeNode* t;
        /* 讓 p 比 q 小 */
        if (p->val > q->val) {
            t = p;
            p = q;
            q = t;
        }
        
        /* p 和 q 在根節點兩側,或者 p 和 q 某一個等於根節點,根節點就是最近公共祖先 */
        if (p->val <= root->val && q->val >= root->val)
        {
            return root;
        }
        
        if(p->val < root->val && q->val < root->val)
        {
            /* p 和 q 都在根節點左側,最近公共祖先肯定在左側 */
            return lowestCommonAncestor(root->left, p, q);
        } else {
            /* p 和 q 都在根節點右側,最近公共祖先肯定在右側 */
            return lowestCommonAncestor(root->right, p, q);
        }
        
    }
};

Valid Anagram 

題意:

Given two strings s and t, write a function to determine if t is an anagram of s.


For example,
s = "anagram", t = "nagaram", return true.
s = "rat", t = "car", return false.

Note:
You may assume the string contains only lowercase alphabets.


思路:

     一個單詞是否可以由另一個單詞重組而成。首先兩個單詞的長度要一樣,其次包含每個字母的個數要一樣。我的想法就是直接使用 map 統計字母的個數就好了。

代碼:

class Solution {
public:
    bool isAnagram(string s, string t) {
        if(s.size() != t.size()) return false;
        
        map<char,int> letter;
        for(int i = 0;i < s.size(); i++) {
            letter[s[i]] ++;
        }
        
        for(int j = 0;j < t.size(); j++) {
            if( --letter[t[j]] < 0) {
                return false;
            }
        }
        
        return true;
        
    }
};

Add Digits

題意:

Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.

For example:

Given num = 38, the process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return it.

Follow up:
Could you do it without any loop/recursion in O(1) runtime?

思路:

    沒有最後的要求的話,肯定是循環+遞歸,done。可是 O(1) 啊...有種直覺肯定是數學規律了...然而沒有想出來...

    真正的 Wiki 在這:https://en.wikipedia.org/wiki/Digital_root 叫做 digital root. 規律爲:

    \operatorname{dr}(n) = \begin{cases}0 & \mbox{if}\ n = 0, \\ 9 & \mbox{if}\ n \neq 0,\ n\ \equiv 0\pmod{9},\\ n\ {\rm mod}\ 9 & \mbox{if}\ n \not\equiv 0\pmod{9}.\end{cases}

     也可以概括爲:\mbox{dr}(n) = 1\ +\ ((n-1)\ {\rm mod}\ 9).\

     其實用了同餘的性質:\mbox{dr}(abc) \equiv a\cdot 10^2 + b\cdot 10 + c \cdot 1 \equiv a\cdot 1 + b\cdot 1 + c \cdot 1 \equiv a + b + c \pmod{9}

代碼:

    遞歸的:

class Solution {
public:
    int addDigits(int num) {
        int ans = 0;
        
        do {
            ans += num % 10;
            num /= 10;
        } while (num);
        
        if(ans / 10) return addDigits(ans);
        else return ans;
        
    }
};
    無遞歸的:

class Solution {
public:
    int addDigits(int num) {
        return 1 + ((num-1)%9);
    }
};


發佈了123 篇原創文章 · 獲贊 268 · 訪問量 111萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章