【leetcode】面试leetcode代码

来源:互联网 发布:csol for mac 编辑:程序博客网 时间:2024/06/10 20:18

  • 字符串

1. leetcode Valid Palindrome

class Solution {public:    bool isPalindrome(string s) {        if (s.size() <= 0) return true;                string::iterator left = s.begin();        string::iterator right = s.end();                while (left < right) {            if (!isalnum(*left)) left++;            else if (!isalnum(*right)) right--;            else {                if (tolower(*left++) != tolower(*right--))                    return false;            }        }                return true;    }};

2. leetcode String to Integer (atoi)

class Solution {public:    int atoi(const char *str) {        if (str == NULL) return -1;                long long res = 0;        int sign = 1;        const char *pStr = str;                while (*pStr != '\0' && isspace(*pStr)) {            pStr++;        }                if (*pStr == '+')             pStr++;        else if (*pStr == '-') {            sign = -1;            pStr++;        }                while (*pStr != '\0') {            if (*pStr<'0' || *pStr>'9') break;                        res = res * 10 + *pStr - '0';                        if (res > INT_MAX) {                if (sign == -1)                    return INT_MIN;                else                    return INT_MAX;            }            pStr++;        }                return sign * res;    }};

3. leetcode Implement strStr()

class Solution {public:    char *strStr(char *haystack, char *needle) {        if (haystack == NULL) return NULL;        if (needle==NULL) return haystack;                char *pSrc = haystack;        char *pSub = needle;                while (*pSrc!='\0' && *pSub!='\0') {            if (*pSrc++ != *pSub++) {                pSub = needle;                pSrc = ++haystack;            }        }                if (*pSub == '\0')            return haystack;                return NULL;    }};


  • 1. leetcode Valid Palindrome
  • 1. leetcode Valid Palindrome
  • 1. leetcode Valid Palindrome
  • 1. leetcode Valid Palindrome
  • 1. leetcode Valid Palindrome
  • 1. leetcode Valid Palindrome
  • 1. leetcode Valid Palindrome
  • 1. leetcode Valid Palindrome

  • 链表

1. leetcode Reverse Nodes in k-Group

class Solution {public:    ListNode *reverseKGroup(ListNode *head, int k) {        if (head==NULL || head->next==NULL || k<=1) return head;                ListNode preHead(-1);        preHead.next = head;        ListNode *pre = &preHead;        ListNode *pTemp;                while (head != NULL) {            ListNode *pEnd = head;            for (int i=1; i<k && head!=NULL; i++) {                head = head->next;            }            if (head == NULL) return preHead.next;            pTemp = pEnd->next;            for (int i=1; i<k; i++) {                ListNode *pNext = pTemp->next;                pTemp->next = pre->next;                pre->next = pTemp;                pTemp = pNext;            }            pre = pEnd;            pEnd->next = pTemp;            head = pTemp;        }                return preHead.next;    }};

2. leetcode Swap Nodes in Pairs

class Solution {public:    ListNode *swapPairs(ListNode *head) {        return swapN(head, 2);    }        ListNode *swapN(ListNode *head, int n) {        if (head==NULL || head->next==NULL || n<=1) return head;                ListNode preHead(-1);        preHead.next = head;        ListNode *pre = &preHead;        ListNode *pFront = head;ListNode *pTemp;                while (pFront != NULL) {            ListNode *pEnd = pFront;            int tempN = n;                        while (pFront && --tempN>0) {                pFront = pFront->next;            }            if (pFront == NULL) return preHead.next;pTemp = pEnd;            for (int i=1; i<n; i++) {pTemp = pTemp->next;                head = pTemp->next;                pTemp->next = pre->next;                pre->next = pTemp;                pTemp = head;            }          pre = pEnd;            pFront = head;            pEnd->next = head;        }                return preHead.next;    }};

3. leetcode Remove Nth Node From End of List

class Solution {public:    ListNode *removeNthFromEnd(ListNode *head, int n) {        if (head==NULL || n<=0) return head;                ListNode preHead(-1);        preHead.next = head;        ListNode *pTemp = &preHead;        head = &preHead;                while (n-->0 && pTemp!=NULL) {            pTemp = pTemp->next;        }        while (pTemp->next != NULL) {            head = head->next;            pTemp = pTemp->next;        }        head->next = head->next->next;                return preHead.next;    }};

4. leetcode Remove Duplicates from Sorted List II

class Solution {public:    ListNode *deleteDuplicates(ListNode *head) {        if (head==NULL || head->next==NULL) return head;                ListNode preHead(-1);        preHead.next = head;        ListNode *rear = &preHead;        ListNode *cur = head;        ListNode *pNext=cur->next;        int flag = 0;                while (pNext != NULL) {            if (cur->val == pNext->val) {                flag = 1;                pNext = pNext->next;            }            else {                if (flag == 1) {                    rear->next = pNext;                    flag = 0;                }                else {                    rear = cur;                }                                cur = pNext;                pNext = pNext->next;            }        }                if (flag == 1)            rear->next = pNext;                return preHead.next;            }};

5. leetcode Remove Duplicates from Sorted List

class Solution {public:    ListNode *deleteDuplicates(ListNode *head) {        if (head==NULL || head->next==NULL) return head;                ListNode *pCur, *pNext;        for (pCur=head, pNext=pCur->next; pNext!=NULL; ) {            if (pCur->val == pNext->val) {                pCur->next = pNext->next;            }            else {                pCur = pNext;            }                        pNext = pNext->next;        }                return head;    }};

6. leetcode Partition List

class Solution {public:    ListNode *partition(ListNode *head, int x) {        if (head==NULL || head->next==NULL) return head;                ListNode left(-1);        ListNode right(-1);        ListNode *pLeft = &left;        ListNode *pRight = &right;                while (head != NULL) {            if (head->val < x) {                pLeft->next = head;                pLeft = pLeft->next;            }            else {                pRight->next = head;                pRight = pRight->next;            }            head = head->next;        }                pRight->next = head;        pLeft->next = right.next;                return left.next;    }};

7. leetcode Reverse Linked List II

class Solution {public:    ListNode *reverseBetween(ListNode *head, int m, int n) {        if (head==NULL || m<=0 || n<=0 || m>=n) return head;                ListNode preHead(-1);        preHead.next = head;        ListNode *pBeg = &preHead;        ListNode *pEnd;        ListNode *pTemp;                for (int i=1; i<=m; i++) {            pTemp = pBeg;            pBeg = pBeg->next;        }                pEnd = pBeg->next;        for (int i=m+1; i<=n; i++) {            head = pEnd->next;            pEnd->next = pTemp->next;            pTemp->next = pEnd;            pEnd = head;        }                pBeg->next = head;        return preHead.next;    }};

8. leetcode Linked List Cycle

class Solution {public:    bool hasCycle(ListNode *head) {        if (head==NULL || head->next==NULL) return false;                ListNode *pFast = head;        ListNode *pSlow = head;                while (pFast!=NULL && pFast->next!=NULL) {            pFast = pFast->next->next;            pSlow = pSlow->next;                        if (pFast == pSlow) return true;        }                return false;    }};

9. leetcode Merge Two Sorted Lists

class Solution {public:    ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {        if (l1 == NULL) return l2;        if (l2 == NULL) return l1;                ListNode preHead(-1);        ListNode *pNew = &preHead;                while (l1 && l2) {            if (l1->val < l2->val) {                pNew->next = l1;                l1 = l1->next;            }            else {                pNew->next = l2;                l2 = l2->next;            }                        pNew = pNew->next;        }        if (l1)            pNew->next = l1;        if (l2)            pNew->next = l2;                return preHead.next;    }};

10. leetcode Sort List

class Solution {public:    ListNode *sortList(ListNode *head) {        if (head==NULL || head->next==NULL) return head;                ListNode *pFast = head;        ListNode *pSlow = head;        ListNode *second;                while (pFast && pFast->next) {            second = pSlow;            pFast = pFast->next->next;            pSlow = pSlow->next;        }                second->next = NULL;                ListNode *l1 = sortList(head);        ListNode *l2 = sortList(pSlow);        head = mergeList(l1, l2);                return head;    }        ListNode *mergeList(ListNode *l1, ListNode *l2) {        if (l1 == NULL) return l2;        if (l2 == NULL) return l1;                ListNode preHead(-1);        ListNode *p = &preHead;                while (l1 && l2) {            if (l1->val < l2->val) {                p->next = l1;                l1 = l1->next;            }            else {                p->next = l2;                l2 = l2->next;            }            p = p->next;        }                if (l1) p->next = l1;        if (l2) p->next = l2;                return preHead.next;    }};

11. leetcode Rotate List

class Solution {public:    ListNode *rotateRight(ListNode *head, int k) {        if (head==NULL || head->next==NULL || k<=0) return head;                ListNode *pPre = head;        ListNode *pTemp;        int len = 0;                while (pPre != NULL) {            len++;            pTemp = pPre;            pPre = pPre->next;        }                k = len - k%len;        pTemp->next = head;        for (int i=0; i<k; i++) {            pTemp = pTemp->next;            head = head->next;        }        pTemp->next = NULL;                return head;    }};

12. leetcode Insertion Sort List

class Solution {public:    ListNode *insertionSortList(ListNode *head) {        if (head==NULL || head->next==NULL) return head;                ListNode preHead(-1);        preHead.next = head;        ListNode *pPre = head->next;        head->next = NULL;                while (pPre != NULL) {            ListNode *first = preHead.next;            ListNode *pNext = pPre->next;            head = &preHead;                        while (first != NULL) {                if (first->val >= pPre->val)                    break;                else {                    head = first;                    first = first->next;                }            }                        pPre->next = head->next;            head->next = pPre;            pPre = pPre->next;            pPre = pNext;        }                return preHead.next;    }};

13. leetcode Reorder List

class Solution {public:    void reorderList(ListNode *head) {        if (head==NULL || head->next==NULL || head->next->next==NULL)            return;                ListNode *pFast = head;        ListNode *pSlow = head;        ListNode *pTemp;                while (pFast!=NULL && pFast->next!=NULL) {            pTemp = pSlow;            pSlow = pSlow->next;            pFast = pFast->next->next;        }pTemp->next = NULL;pSlow = reverseList(pSlow);        head = mergeList(head, pSlow);    }        ListNode *reverseList(ListNode *head) {        if (head==NULL || head->next==NULL) return head;                ListNode *pCur = head->next;        ListNode *pNext;        head->next = NULL;                while (pCur != NULL) {            pNext = pCur->next;            pCur->next = head;            head = pCur;            pCur = pNext;        }return head;    }        ListNode *mergeList(ListNode *l1, ListNode *l2) {        if (l1 == NULL) return l2;        if (l2 == NULL) return l1;                ListNode preHead(-1);        ListNode *pTemp = &preHead;                while (l1 && l2) {            pTemp->next = l1;            l1 = l1->next;            pTemp = pTemp->next;            pTemp->next = l2;            pTemp = pTemp->next;            l2 = l2->next;        }        if (l1 != NULL) pTemp->next = l1;if (l2 != NULL) pTemp->next = l2;return preHead.next;    }};

14. leetcode LRU Cache

class LRUCache{private:    struct CacheNode {        int key;        int value;        struct CacheNode *prev;        struct CacheNode *next;        CacheNode(int k, int v) :key(k), value(v) {}    };    public:    LRUCache(int capacity) {        this->capacity = capacity;    }        int get(int key) {        if (cacheMap.find(key) == cacheMap.end()) return -1;                cacheList.splice(cacheList.begin(), cacheList, cacheMap[key]);        cacheMap[key] = cacheList.begin();        return cacheMap[key]->value;    }        void set(int key, int value) {        if (cacheMap.find(key) == cacheMap.end()) {            if (cacheList.size() == capacity) {                cacheMap.erase(cacheList.back().key);                cacheList.pop_back();            }                        cacheList.push_front(CacheNode(key, value));            cacheMap[key] = cacheList.begin();         }        else {            cacheMap[key]->value = value;            cacheList.splice(cacheList.begin(), cacheList, cacheMap[key]);            cacheMap[key] = cacheList.begin();        }    }private:    list<CacheNode> cacheList;    unordered_map<int, list<CacheNode>::iterator> cacheMap;    int capacity;};

15. leetcode Linked List Cycle II

class Solution {public:    ListNode *detectCycle(ListNode *head) {        if (head == NULL) return NULL;                ListNode *pFast = head;        ListNode *pSlow = head;        ListNode *pHead = head;                while (pFast && pFast->next) {            pFast = pFast->next->next;            pSlow = pSlow->next;                         if (pFast == pSlow) {                while (pHead != pSlow) {                    pHead = pHead->next;                    pSlow = pSlow->next;                }                return pHead;            }        }                return NULL;    }};


1. leetcode Valid Palindrome
1. leetcode Valid Palindrome

1. leetcode Maximum Depth of Binary Tree

class Solution {public:    int maxDepth(TreeNode *root) {        if (root == NULL)            return 0;        if (root->left==NULL && root->right==NULL)            return 1;                    return max(maxDepth(root->left), maxDepth(root->right)) + 1;    }};

2. leetcode Same Tree

class Solution {public:    bool isSameTree(TreeNode *p, TreeNode *q) {        if (p==NULL && q==NULL)            return true;        if ((p==NULL && q!=NULL) || (p!=NULL && q==NULL))            return false;                    if (p->val == q->val) {                        return isSameTree(p->left, q->left) && isSameTree(p->right, q->right);        }        else            return false;    }};

3. leetcode Balanced Binary Tree

class Solution {public:    bool isBalanced(TreeNode *root) {        if (root == NULL) return true;                int left = heightTree(root->left) + 1;        int right = heightTree(root->right) + 1;        return (abs(left-right)<=1) && isBalanced(root->left) && isBalanced(root->right);            }        int heightTree(TreeNode *root) {        if (root == NULL) return 0;        if (root->left==NULL && root->right==NULL) return 1;                return max(heightTree(root->left), heightTree(root->right)) + 1;    }};

4. leetcode Binary Tree Preorder Traversal

class Solution {public:    vector<int> preorderTraversal(TreeNode *root) {        vector<int> res;        stack<TreeNode *> sTemp;                if (root == NULL) return res;                sTemp.push(root);        while (!sTemp.empty()) {            TreeNode *temp = sTemp.top();            res.push_back(temp->val);            sTemp.pop();                        if (temp->right) sTemp.push(temp->right);            if (temp->left) sTemp.push(temp->left);        }                return res;     }};

5. leetcode Binary Tree Inorder Traversal

class Solution {public:    vector<int> inorderTraversal(TreeNode *root) {        vector<int> res;        stack<TreeNode *> sTemp;        TreeNode *pRoot = root;                while (pRoot!=NULL || !sTemp.empty()) {            while (pRoot) {                sTemp.push(pRoot);                pRoot = pRoot->left;            }                        if (!sTemp.empty()) {                TreeNode *temp = sTemp.top();                res.push_back(temp->val);                sTemp.pop();                                if (temp->right) {                    pRoot = temp->right;                }            }        }                return res;    }};

6. leetcode Binary Tree Postorder Traversal

class Solution {public:    vector<int> postorderTraversal(TreeNode *root) {        vector<int> res;        stack<TreeNode *> sTemp;        TreeNode *pCur = root;        TreeNode *pPre = NULL;                while (pCur!=NULL || !sTemp.empty()) {            while (pCur != NULL) {                sTemp.push(pCur);                pCur = pCur->left;            }            pCur = sTemp.top();                        if (pCur->right==NULL || pCur->right==pPre) {                res.push_back(pCur->val);                pPre = pCur;                sTemp.pop();                pCur = NULL;            }            else                pCur = pCur->right;        }                return res;    }};

7. leetcode Binary Tree Level Order Traversal

class Solution {public:    vector<vector<int> > levelOrder(TreeNode *root) {        vector<vector<int> > res;        vector<int> vec;        if (root == NULL) return res;                queue<TreeNode *> curQueue, nextQueue;        curQueue.push(root);                while (!curQueue.empty()) {            while (!curQueue.empty()) {                TreeNode *temp = curQueue.front();                vec.push_back(temp->val);                curQueue.pop();                                if (temp->left) nextQueue.push(temp->left);                if (temp->right) nextQueue.push(temp->right);            }                        swap(curQueue, nextQueue);            res.push_back(vec);            vec.clear();        }                return res;    }};

8. leetcode Binary Tree Zigzag Level Order Traversal

class Solution {public:    vector<vector<int> > zigzagLevelOrder(TreeNode *root) {        vector<vector<int> > res;        if (root == NULL) return res;                queue<TreeNode *> cur, nex;        cur.push(root);        bool isReverse = false;                while (!cur.empty()) {            vector<int> vec;            while (!cur.empty()) {                TreeNode *temp = cur.front();                vec.push_back(temp->val);                cur.pop();                if (temp->left) nex.push(temp->left);                if (temp->right) nex.push(temp->right);            }                        if (isReverse == false) {                isReverse = true;            }            else {                isReverse = false;                reverse(vec.begin(), vec.end());            }            res.push_back(vec);            swap(cur, nex);        }                return res;    }};

9. leetcode Validate Binary Search Tree

class Solution {public:    bool isValidBST(TreeNode *root) {        return isValid(root, INT_MIN, INT_MAX);    }        bool isValid(TreeNode *root, int le, int ri) {        if (root == NULL) return true;        if (!(root->val>le && root->val<ri)) return false;                return isValid(root->left, le, root->val) && isValid(root->right, root->val, ri);    }};

10. leetcode Binary Tree Level Order Traversal II

class Solution {public:    vector<vector<int> > levelOrderBottom(TreeNode *root) {        vector<vector<int> > res;        if (root == NULL) return res;                queue<TreeNode *> cur, nex;        cur.push(root);                while (!cur.empty()) {            vector<int> vec;            while (!cur.empty()) {                TreeNode *temp = cur.front();                cur.pop();                vec.push_back(temp->val);                if (temp->left) nex.push(temp->left);                if (temp->right) nex.push(temp->right);            }                        res.push_back(vec);            swap(cur, nex);        }                reverse(res.begin(), res.end());        return res;    }};

11. leetcode Sum Root to Leaf Numbers

class Solution {public:    int sumNumbers(TreeNode *root) {        return dfs(root, 0);    }        int dfs(TreeNode *root, int sum) {        if (root==NULL) return 0;        if (root->left==NULL && root->right==NULL)             return sum*10 + root->val;                    return dfs(root->left, sum*10 + root->val) + dfs(root->right, sum*10 + root->val);    }};

12. leetcode Recover Binary Search Tree

class Solution {public:    void recoverTree(TreeNode *root) {        TreeNode *s1 = NULL;        TreeNode *s2 = NULL;        TreeNode *pre = NULL;                findTwo(root, s1, s2, pre);                if (s1!=NULL && s2!=NULL) {            swap(s1->val, s2->val);        }    }        void findTwo(TreeNode *root, TreeNode *&s1, TreeNode *&s2, TreeNode *&pre) {        if (root == NULL) return;                findTwo(root->left, s1, s2, pre);                if (pre!=NULL && pre->val > root->val) {            s2 = root;            if (s1 == NULL)                s1 = pre;        }                pre = root;        findTwo(root->right, s1, s2, pre);    }};

13. leetcode Symmetric Tree

class Solution {public:    bool isSymmetric(TreeNode *root) {        if (root == NULL) return true;                return isLeftRight(root->left, root->right);    }        bool isLeftRight(TreeNode *le, TreeNode *ri) {        if (le==NULL && ri==NULL) return true;        if (le==NULL || ri==NULL) return false;                if (le->val != ri->val) return false;                return isLeftRight(le->left, ri->right) && isLeftRight(le->right, ri->left);    }};

14. leetcode Flatten Binary Tree to Linked List

class Solution {public:    void flatten(TreeNode *root) {        if (root == NULL) return;                while (root) {            if (root->left) {                TreeNode *pre = root->left;                while (pre->right)                     pre = pre->right;                                    pre->right = root->right;                root->right = root->left;                root->left = NULL;            }            root = root->right;        }    }};

15. leetcode Populating Next Right Pointers in Each Node II

class Solution {public:    void connect(TreeLinkNode *root) {        if (root == NULL) return;                queue<TreeLinkNode *> cur, nex;        cur.push(root);                while (!cur.empty()) {            TreeLinkNode preHead(-1);            TreeLinkNode *p = &preHead;                        while (!cur.empty()) {                TreeLinkNode *temp = cur.front();                cur.pop();                p->next = temp;                p = p->next;                if (temp->left) nex.push(temp->left);                if (temp->right) nex.push(temp->right);            }                        p->next = NULL;            swap(cur, nex);        }    }};

16. leetcode Populating Next Right Pointers in Each Node

class Solution {public:    void connect(TreeLinkNode *root) {        if (root == NULL) return;        queue<TreeLinkNode *> cur, nex;        cur.push(root);                while (!cur.empty()) {            TreeLinkNode preHead(-1);            TreeLinkNode *p = &preHead;            while (!cur.empty()) {                TreeLinkNode *temp = cur.front();                cur.pop();                p->next = temp;                p = p->next;                if (temp->left) nex.push(temp->left);                if (temp->right) nex.push(temp->right);            }            p->next = NULL;            swap(cur, nex);        }    }};

17. leetcode Construct Binary Tree from Preorder and Inorder Traversal

class Solution {public:    TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) {        if (preorder.empty() || inorder.empty() || preorder.size()!=inorder.size())            return NULL;                    return buildT(preorder, 0, preorder.size()-1, inorder, 0, inorder.size()-1);    }        TreeNode *buildT(vector<int> &preorder, int pBeg, int pEnd, vector<int> &inorder, int iBeg, int iEnd) {        if (pBeg > pEnd || iBeg > iEnd) return NULL;                TreeNode *root = new TreeNode(preorder[pBeg]);        int pos = -1;        for (pos=iBeg; pos<=iEnd; pos++) {            if (inorder[pos] == root->val)                break;        }                root->left = buildT(preorder, pBeg+1, pBeg+pos-iBeg, inorder, iBeg, pos-1);        root->right = buildT(preorder, pBeg+pos-iBeg+1, pEnd, inorder, pos+1, iEnd);                return root;    }};

18. leetcode Construct Binary Tree from Inorder and Postorder Traversal

class Solution {public:    TreeNode *createTree(vector<int> &inorder, int inBeg, int inEnd, vector<int> &postorder, int postBeg, int postEnd) {        if (inBeg > inEnd)            return NULL;        int root = postorder[postEnd];        TreeNode *node = new TreeNode(root);        int index;        for(int i = inBeg; i <= inEnd; i++)            if (inorder[i] == root) {                index = i; break;        }                int len = index - inBeg;        node->left = createTree(inorder, inBeg, index - 1, postorder, postBeg, postBeg + len - 1);        node->right = createTree(inorder, index + 1, inEnd, postorder, postBeg + len, postEnd - 1);        return node;    }    TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) {        if (inorder.size() == 0)            return NULL;        return createTree(inorder, 0, inorder.size() - 1, postorder, 0, postorder.size() - 1);    }};

19. leetcode Minimum Depth of Binary Tree

class Solution {public:    int minDepth(TreeNode *root) {        if (root == NULL) return 0;        if (root->left==NULL && root->right==NULL) return 1;        if (root->left==NULL && root->right!=NULL) return minDepth(root->right) + 1;        if (root->right==NULL && root->left!=NULL) return minDepth(root->left) + 1;                return min(minDepth(root->left), minDepth(root->right)) + 1;    } };

20. leetcode Path Sum

class Solution {public:    bool hasPathSum(TreeNode *root, int sum) {        bool res = false;        pathSum(root, sum, 0, res);        return res;    }        void pathSum(TreeNode *root, int sum, int res, bool &fal_tru) {        if (root == NULL) return;                if (root->left==NULL && root->right==NULL) {            if (sum == res + root->val) {                fal_tru = true;                return;            }        }        if (root->left && fal_tru==false)            pathSum(root->left, sum, res+root->val, fal_tru);        if (root->right && fal_tru==false)            pathSum(root->right, sum, res+root->val, fal_tru);    } };

21. leetcode Path Sum II

class Solution {public:    vector<vector<int> > pathSum(TreeNode *root, int sum) {        vector<vector<int> > res;        vector<int> temp;        pathT(root, sum, 0, res, temp);        return res;    }        void pathT(TreeNode *root, int sum, int num, vector<vector<int> > &res, vector<int> &temp) {        if (root == NULL) return;        if (root->left==NULL && root->right==NULL) {            if (sum == num + root->val) {                temp.push_back(root->val);                res.push_back(temp);                temp.pop_back();            }            return;        }                temp.push_back(root->val);        pathT(root->left, sum, num+root->val, res, temp);        pathT(root->right, sum, num+root->val, res, temp);        temp.pop_back();    }};

22. leetcode Binary Tree Maximum Path Sum

class Solution {public:    int dfs(TreeNode *root) {        if (root == NULL) return 0;                int l = dfs(root->left);        int r = dfs(root->right);        int sumTemp = root->val;        if (l > 0) sumTemp += l;        if (r > 0) sumTemp += r;                maxResult = max(maxResult, sumTemp);        return max(l, r)>0 ? max(l, r) + root->val : root->val;    }    int maxPathSum(TreeNode *root) {        if (root == NULL) return 0;        maxResult = INT_MIN;        dfs(root);        return maxResult;    }private:    int maxResult;};

23. leetcode Convert Sorted Array to Binary Search Tree

class Solution {public:    TreeNode *sortTOBST(vector<int> &num, int beg, int end) {        if (beg > end) return NULL;        int mid = (beg + end)/2;        TreeNode *root = new TreeNode(num[mid]);        root->left = sortTOBST(num, beg, mid - 1);        root->right = sortTOBST(num, mid + 1, end);                return root;    }    TreeNode *sortedArrayToBST(vector<int> &num) {        if (num.empty()) return NULL;                return sortTOBST(num, 0, num.size() - 1);    }};

24. leetcode Convert Sorted List to Binary Search Tree

class Solution {public:    TreeNode *sortedListToBST(ListNode *head) {        if (head == NULL) return NULL;         TreeNode *root;                 if (head->next == NULL) {          root = new TreeNode(head->val);        }        else {            ListNode *pFast = head;            ListNode *pSlow = head;            ListNode *pTemp = pSlow;                        while (pFast!=NULL && pFast->next!=NULL) {                pFast = pFast->next->next;                pTemp = pSlow;                pSlow = pSlow->next;            }            pTemp->next = NULL;            pFast = pSlow->next;                        root = new TreeNode(pSlow->val);            root->left = sortedListToBST(head);            root->right = sortedListToBST(pFast);        }                return root;    }};

25. leetcode Unique Binary Search Trees

class Solution {public:    int retNum(int dp[], int beg, int end) {        if (beg > end) return 1;                if (dp[end-beg+1] != 0)             return dp[end-beg+1];                    int res = 0;        for (int i=beg; i<=end; i++) {            int leftNum = retNum(dp, beg, i - 1);            int rightNum = retNum(dp, i + 1, end);            res += leftNum * rightNum;        }                return (dp[end-beg+1] = res);    }    int numTrees(int n) {        if (n <=0) return 0;                int dp[n + 1];        memset(dp, 0, sizeof(dp));        return retNum(dp, 1, n);    }};

26. leetcode Unique Binary Search Trees II

class Solution {public:    vector<TreeNode *> genTrees(int beg, int end) {        vector<TreeNode *> res;        if (beg > end) {            res.push_back(NULL);            return res;        }                for (int i=beg; i<=end; i++) {            vector<TreeNode *> lVec = genTrees(beg, i - 1);            vector<TreeNode *> rVec = genTrees(i + 1, end);                        for (int j=0; j<lVec.size(); j++) {                for (int k=0; k<rVec.size(); k++) {                   TreeNode *root = new TreeNode(i);                    root->left = lVec[j];                   root->right = rVec[k];                   res.push_back(root);                }            }        }                return res;    }    vector<TreeNode *> generateTrees(int n) {        return genTrees(1, n);    }};


  • 数组

1. leetcode Climbing Stairs

class Solution {public:    int climbStairs(int n) {        if (n <= 0) return 0;                int first = 0;         int second = 1;        int res;                for (int i=1; i<=n; i++) {            res = first + second;            first = second;            second = res;        }                return res;    }};

2. leetcode Single Number

class Solution {public:    int singleNumber(int A[], int n) {        if (A==NULL || n<=0)            return -1;                    int res = A[0];        for (int i=1; i<n; i++)            res ^= A[i];                    return res;    }};

3. leetcode Merge Sorted Array

class Solution {public:    void merge(int A[], int m, int B[], int n) {        int i_A = m-1;        int i_B = n-1;        int i_total = m + n - 1;                while (i_A>=0 && i_B>=0) {            if (A[i_A] > B[i_B]) {                A[i_total--] = A[i_A--];            }            else {                A[i_total--] = B[i_B--];            }        }                while (i_B >= 0)            A[i_total--] = B[i_B--];    }};

4. leetcodeRemove Element

class Solution {public:    int removeElement(int A[], int n, int elem) {        int pos = 0;        for (int i=0; i<n; i++) {            if (A[i] != elem) {                A[pos++] = A[i];            }        }                return pos;    }};

5. leetcodeSpiral Matrix

class Solution {public:    vector<int> spiralOrder(vector<vector<int> > &matrix) {        vector<int> res;        if (matrix.empty())            return res;                    int s_row = 0, e_row=matrix.size() - 1;        int s_col = 0, e_col = matrix[0].size() - 1;        while (s_row<=e_row && s_col<=e_col) {            if (s_row<=e_row && s_col<=e_col) { //right                for (int i=s_col; i<=e_col; i++) {                    res.push_back(matrix[s_row][i]);                }                s_row++;            }            if (s_row<=e_row && s_col<=e_col) { //down                for (int i=s_row; i<=e_row; i++) {                    res.push_back(matrix[i][e_col]);                }                e_col--;            }            if (s_row<=e_row && s_col<=e_col) { //left                for (int i=e_col; i>=s_col; i--) {                    res.push_back(matrix[e_row][i]);                }                e_row--;            }            if (s_row<=e_row && s_col<=e_col) {                for (int i=e_row; i>=s_row; i--) {                    res.push_back(matrix[i][s_col]);                }                s_col++;            }        }        return res;    }};

6. leetcode Spiral Matrix II

class Solution {public:    vector<vector<int> > generateMatrix(int n) {        vector<vector<int> >res;        vector<int> temp;        int m = 1;        if (n <= 0)            return res;        int s_row = 0, e_row = n-1, s_col = 0, e_col = n-1;        for (int i=0; i<n; i++)            temp.push_back(0);                for (int i=0; i<n; i++)            res.push_back(temp);        while (s_row<=e_row && s_col<=e_col) {            for (int i=s_col; i<=e_col; i++) {                res[s_row][i] = m++;            }            s_row++;            for (int i=s_row; i<=e_row; i++) {                res[i][e_col] = m++;            }            e_col--;            for (int i=e_col; i>=s_col; i--)                res[e_row][i] = m++;            e_row--;            for (int i=e_row; i>=s_row; i--) //up                res[i][s_col] = m++;            s_col++;        }        return res;    }};

7. leetcode Permutations

class Solution {public:    bool nextPermutation(vector<int> &num) {        if (num.empty()) return false;        int head_item;        int item;        int len = num.size() - 1;                for (item=num.size()-1; item>0; item--) {            if (num[item-1] < num[item])                break;        }        if (item == 0) return false;        head_item = item - 1;                for (item=num.size()-1; item>head_item; item--) {            if (num[head_item] < num[item])                break;        }        swap(num[head_item], num[item]);        for (item=head_item+1; item<=len; item++, len--) {            swap(num[item], num[len]);        }        return true;    }    vector<vector<int> > permute(vector<int> &num) {        vector<vector<int> > ret;        if (num.empty()) return ret;                sort(num.begin(), num.end());        ret.push_back(num);        while (nextPermutation(num)) {            ret.push_back(num);        }        return ret;    }};

8. leetcode Permutations II

class Solution {public:    bool nextPermutation(vector<int> &num) {        if (num.empty()) return false;        int head_item;        int item;        int len = num.size() - 1;                for (item=num.size()-1; item>0; item--) {            if (num[item-1] < num[item])                break;        }        if (item == 0) return false;        head_item = item - 1;                for (item=num.size()-1; item>head_item; item--) {            if (num[head_item] < num[item])                break;        }        swap(num[head_item], num[item]);        for (item=head_item+1; item<=len; item++, len--) {            swap(num[item], num[len]);        }        return true;    }        vector<vector<int> > permuteUnique(vector<int> &num) {        vector<vector<int> > ret;        if (num.empty()) return ret;                sort(num.begin(), num.end());        ret.push_back(num);        while (nextPermutation(num))             ret.push_back(num);                    return ret;    }};

9. leetcode Next Permutation

class Solution {public:    bool nextPermu(vector<int> &num) {        if (num.empty()) return false;        int head_item;        int item;        int len = num.size() - 1;                for (item=num.size()-1; item>0; item--) {            if (num[item-1] < num[item])                break;        }        if (item == 0) return false;        head_item = item - 1;                for (item=num.size()-1; item>head_item; item--) {            if (num[head_item] < num[item])                break;        }        swap(num[head_item], num[item]);        for (item=head_item+1; item<=len; item++, len--) {            swap(num[item], num[len]);        }        return true;    }        void nextPermutation(vector<int> &num) {        if (num.empty()) return;        if (nextPermu(num) == false) {            sort(num.begin(), num.end());        }     }};

10. leetcode Remove Duplicates from Sorted Array

class Solution {public:    int removeDuplicates(int A[], int n) {        if (A==NULL || n<0) return -1;        if (n == 0) return 0;                int start = 0;        for (int i=1; i<n; i++) {            if (A[start] != A[i])                 A[++start] = A[i];        }                return start + 1;    }};

11. leetcode Pascal's Triangle

class Solution {public:    vector<vector<int> > generate(int numRows) {        vector<vector<int> > ret;        if (numRows <= 0) return ret;                vector<int> temp;        temp.push_back(1);        ret.push_back(temp);                for (int i=1; i<numRows; i++) {            temp.clear();            temp.push_back(1);            for (int j=1; j<i; j++) {                int iTemp = ret[i-1][j-1] + ret[i-1][j];                temp.push_back(iTemp);            }            temp.push_back(1);            ret.push_back(temp);        }                return ret;    }}

12. leetcode Pascal's Triangle II

class Solution {public:    vector<int> getRow(int rowIndex) {        vector<int> ret;        vector<int> pre;        if (rowIndex < 0) return ret;                ret.push_back(1);        for (int i=1; i<=rowIndex; i++) {            pre = ret;            ret.clear();            ret.push_back(1);                        for (int j=1; j<i; j++) {                int iTemp = pre[j-1] + pre[j];                ret.push_back(iTemp);            }                        ret.push_back(1);        }        return ret;    }};


1. leetcode Valid Palindrome

1. leetcode Valid Palindrome

1. leetcode Valid Palindrome

1. leetcode Valid Palindrome

  • 动态规划

1. leetcode Maximum Subarray

class Solution {public:    int maxSubArray(int A[], int n) {        if (A==NULL || n<=0) return -1;                int res = A[0];        int current = 0;                for (int i=0; i<n; i++) {            current += A[i];                            if (res < current)                res = current;            if (current < 0)                current = 0;        }                return res;    }};

2. leetcode Triangle

class Solution {public:    int minimumTotal(vector<vector<int> > &triangle) {        if (triangle.size() <= 0) return 0;                for (int i=triangle.size()-2; i>=0; i--) {            for (int j=0; j<=i; j++) {                triangle[i][j] += min(triangle[i+1][j], triangle[i+1][j+1]);            }        }                return triangle[0][0];    }};

3. leetcode Edit Distance

class Solution {public:    int minDistance(string word1, string word2) {        int len1 = word1.size();        int len2 = word2.size();        int res[len1 + 1][len2 + 1];                for (int i=0; i<=len2; i++)            res[0][i] = i;        for (int i=0; i<=len1; i++)             res[i][0] = i;                    for (int i=0; i<len1; i++) {            for (int j=0; j<len2; j++) {                if (word1[i] == word2[j])                     res[i + 1][j + 1] = res[i][j];                else {                    res[i + 1][j + 1] = min(res[i + 1][j], res[i][j + 1]) + 1;                    res[i + 1][j + 1] = min(res[i + 1][j + 1], res[i][j] + 1);                }            }        }                return res[len1][len2];    }};


1. leetcode Valid Palindrome

  • 分治

1. leetcode Sqrt(x)

class Solution {public:    int sqrt(int x) {        if (x < 0) return -1;        if (x <= 1) return x;                int left = 1;        int right = x / 2;        int last;                while (left <= right) {            int mid = (left + right) / 2;                        if (x/mid == mid) return mid;            else if (x/mid < mid) right = mid - 1;            else {                left = mid + 1;                last = mid;            }        }                return last;    }};

2. leetcodePow(x, n)

class Solution {public:    double pow(double x, int n) {        if (n < 0) return 1.0 / powNext(x, -n);                return powNext(x, n);    }        double powNext(double x, int n) {        if (n == 0) return 1.0;                double res = powNext(x, n/2);        if (n%2 == 1)             return res * res * x;        else            return res * res;    }};

  • 贪心法

1. leetcode Best Time to Buy and Sell Stock

class Solution {public:    int maxProfit(vector<int> &prices) {        if (prices.size() < 2) return 0;        int ret = 0;        int cur_min = prices[0];                        for (int i=1; i<prices.size(); i++) {            ret = max (ret, prices[i] - cur_min);            cur_min = min(cur_min, prices[i]);        }                return ret;    }};

2. leetcode Best Time to Buy and Sell Stock II

class Solution {public:    int maxProfit(vector<int> &prices) {         if (prices.size() < 2) return 0;        int profit = 0;                for (int i=1; i<prices.size(); i++) {            int temp = prices[i] - prices[i - 1];            if (temp > 0)                profit += temp;        }                return profit;    }};


  • 细节实现

1. leetcode Reverse Integer

class Solution {public:    int reverse(int x) {        int sign = 1;        int res = 0;                if (x < 0) {            sign = -1;            x = -x;        }        while (x) {            res = res * 10 + x%10;            x /= 10;        }                return res * sign;    }};


1. leetcode Valid Palindrome

1. leetcode Valid Palindrome
1. leetcode Valid Palindrome




1. leetcode Valid Palindrome
1. leetcode Valid Palindrome



  • 其他实现

1. IP字符串转换整数

int retLongIP(const char *strIP) {if (strIP==NULL || strlen(strIP)<7 || strlen(strIP)>15)return -1;int res = 0;int dot = 0;int shift = 24;const char *pBeg = strIP;const char *pEnd = strIP;while (*pEnd != '\0') {int temp = 0;while (*pEnd!='\0' && *pEnd!='.'){if (*pEnd>='0' && *pEnd<='9') {temp = temp * 10 + (*pEnd - '0');pEnd++;}elsereturn -1;}if (*pEnd == '.') {dot += 1;}if (pBeg==pEnd || (temp<0 && temp>255) || (*pBeg=='0' && pEnd-pBeg>1))return -1;res += (temp<<shift);shift -= 8;if (*pEnd != '\0')pBeg = ++pEnd;}if (dot != 3) return -1;return res;}

2. leetcode 约瑟夫问题

#include <stdio.h>#include <stdlib.h>#include <string.h>void yueSeFu(int a[], int n, int m) {if (a==NULL || n<=0) return;int count = n; int i = 0; //nint j = 0; //mwhile (count != 0) {if (a[i] != 0) {j++;if (j%m == 0) {j = 0;printf("%d\n", a[i]);a[i] = 0;count--;}}i++;if (i%n == 0)i = 0;}}int main(){int n, m, i;scanf("%d %d", &n, &m);int *pN = (int *)malloc(sizeof(int) * (n));if (pN == NULL)exit(-1);for (i=0; i<n; i++) {pN[i] = i + 1;}yueSeFu(pN, n, m);return 0;}

3. leetcode KMP

求模式 a b a a b c a c的next函数的算法:因为已知next(1)=0,只要找出next(j+1)与next(j)之间的关系,就可以求出模式串所有next。
<span style="font-family: Arial, Helvetica, sans-serif; font-size: 12px;">next初始算法::::</span>
(1)next[j] = 0 j=1
(2)设next[j]=k, 于是有p(1)...p(k-1) = p(j-k+1)...p(j-1)
     若p(k) = p(j) 必然有<span style="font-family: Arial, Helvetica, sans-serif; font-size: 12px;">p(1)...p(k-1)p(k) = p(j-k+1)...p(j-1)p(j)  next[j+1] = next[j] + 1 = k +1</span>
<span style="font-family: Arial, Helvetica, sans-serif; font-size: 12px;">         若不等   </span>
void get_next(sstring T, int &next[]){  //求模式串T的next函数值并存入数组next。  j=1; k=next[j]=0;  while (j<T[0])  {  //计算next(j)从next(2)到next(T[0]),T[0]是T的长度                    //但并不意味着只循环m-1次,因为在循环体中j的值可能不发生变化    if (k==0||T[j]==T[k])// 没有重叠真子串和(有重叠真子串但T[j]==T[k])时//都应该得出next(j+1)的值      next[++j]=++k;    else k=next(k);//否则,得不出next(j+1)的值,所以j不变,k退回到next(k),重复匹配。}
利用next值表进行匹配的过程:假设以i和j分别指示主串和模式串中正待比较的字符,若si=tj ,则i和j分别增1,否则,i不变,而j退回到next[j]的位置再比较,若j退回到值为0(即模式的第一个字符失配),则将模式继续向右滑动一个位置,即从主串的下一个字符si+1起和模式重新开始匹配。int index_KMP(sstring s, sstring t, int pos){   //利用模式串的next函数求t在主串s中第pos个字符之后的位置的KMP算法,   //t非空,1<=pos<=strlength(s)   i=pos; j=1;   while(i<=s[0]&&j<=t[0])   {   if (j==0||s[i]==t[j]){++i;++j;}   else j=next[j];}if (j>t[0]) return i-t[0];else return 0;}//index_kmp



1. leetcode Valid Palindrome
1. leetcode Valid Palindrome




八.  

Search in Rotated Sorted Array II

 


class Solution {
public:
    bool search(int A[], int n, int target) {
        int pre = 0, last = n - 1;


        while (pre <= last) {
            const int mid = (pre + last) / 2;
            if (A[mid] == target)
                return true;
            if (A[pre] < A[mid]) {
                if (A[pre] <= target && A[mid] >= target)
                    last = mid;
                else
                    pre = mid;
            }
            else if (A[pre] > A[mid]) {
                if (target >= A[mid] && target <= A[last])
                    pre = mid;
                else
                    last = mid;
            }
            else {
                pre++;
            }
        }


        return false;
    }
};



//leetcode Queen

class Solution {
public:
    vector<vector<string> > solveNQueens(int n) {
        vector<vector<string> > res; vector<string> temp;
        string ss(n, '.');
        if (n <= 0)
            return res;


        for (int i=0; i<n; i++) {
            temp.push_back(ss);
        }


        for (int i=0; i<=n; i++) {
            row[i] = true;
            mark[i] = 0;
        }
        for (int i=0; i<=2*n-1; i++)
            line1[i] = line2[i] = true;


        tryToQueen(0, n, res, temp);


        return res;
    }


    void tryToQueen(int start, int n, vector<vector<string> > &res, vector<string> &temp) {
        if (start == n) { //result
            vector<string> tempT(temp);
            for (int i=0; i<n; i++) {
                int nrow = mark[i];
                tempT[nrow][i] = 'Q';
            }
            res.push_back(tempT);
            return;
        }
        for (int j=0; j<n; j++) {
            if (row[j] && line1[start + j] && line2[start - j + n]) {
                mark[start] = j;
                row[j] = line1[start + j] = line2[start - j + n] = false;
                tryToQueen(start+1, n, res, temp);
                row[j] = line1[start + j] = line2[start - j + n] = true;
            }
        }
    }


    bool row[20]; int mark[20];
    bool line1[40]; bool line2[40];
};



0 0
原创粉丝点击