From a81f28cc73c3c6f91cacf21e4cdc0384f3b29616 Mon Sep 17 00:00:00 2001 From: Ranger Date: Sat, 15 Aug 2015 17:39:23 +0800 Subject: [PATCH 01/57] Maximum Depth of Binary Tree --- 104.txt | 20 ++++++++++ btsearch.cpp | 76 ------------------------------------- graphSearch.cpp | 99 ------------------------------------------------- 3 files changed, 20 insertions(+), 175 deletions(-) create mode 100644 104.txt delete mode 100644 btsearch.cpp delete mode 100644 graphSearch.cpp diff --git a/104.txt b/104.txt new file mode 100644 index 0000000..8832aff --- /dev/null +++ b/104.txt @@ -0,0 +1,20 @@ +//Maximum Depth of Binary Tree + +/** + * 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 maxDepth(TreeNode* root) { + if (root == NULL) + return 0; + else + return 1 + max(maxDepth(root->left), maxDepth(root->right)); + } +}; \ No newline at end of file diff --git a/btsearch.cpp b/btsearch.cpp deleted file mode 100644 index f908d6f..0000000 --- a/btsearch.cpp +++ /dev/null @@ -1,76 +0,0 @@ -#include -#include -#include -using namespace std; - -int index = 0; - -typedef struct Node -{ - char data; - struct Node *lchild; - struct Node *rchild; -}* Tree; - -void treeConstructor(Tree &node, char data[]) -{ - char e = data[index++]; - if(e == '#') - node = nullptr; - else - { - node = new Node; - node->data = e; - treeConstructor(node->lchild, data); - treeConstructor(node->rchild, data); - } -} - -void DFS(Tree root) -{ - stack nodeStack; - nodeStack.push(root); - Node *node; - while(!nodeStack.empty()) - { - node = nodeStack.top(); - cout << node->data; - nodeStack.pop(); - if(node->rchild) - nodeStack.push(node->rchild); - if(node->lchild) - nodeStack.push(node->lchild); - } -} - -void BFS(Tree root) -{ - queuenodeQueue; - nodeQueue.push(root); - Node *node; - while(!nodeQueue.empty()) - { - node = nodeQueue.front(); - cout << node->data; - nodeQueue.pop(); - if(node->lchild) - nodeQueue.push(node->lchild); - if(node->rchild) - nodeQueue.push(node->rchild); - } -} - -int main() -{ - char data[16] = {'A', 'B', 'D', '#', '#', 'E', '#', '#', 'C', 'F', '#', '#', 'G', '#', '#', '\0'}; - Tree root; - treeConstructor(root, data); - cout << "DFS: "; - DFS(root); - cout << endl; - cout << "DFS: "; - BFS(root); - cout << endl; - - return 0; -} diff --git a/graphSearch.cpp b/graphSearch.cpp deleted file mode 100644 index ff144a0..0000000 --- a/graphSearch.cpp +++ /dev/null @@ -1,99 +0,0 @@ -#include -#include -#include -using namespace std; - -const int vnum = 5; -int visited[vnum]; - -struct Graph -{ - int vertex[vnum]; - int arc[vnum][vnum]; -}; - -void CreatGraph(Graph &G, int data[], int maxtrix[][vnum]) -{ - for(int i = 0; i < vnum; i++) - G.vertex[i] = data[i]; - for(int i = 0; i < vnum; i++) - for(int j = 0; j < vnum; j++) - G.arc[i][j] = maxtrix[i][j]; -} - -void DFS(Graph *G, int v) -{ - if(!visited[v]) - { - cout << G->vertex[v]; - visited[v] = 1; - } - for(int i = 0; i < vnum; i++) - if(G->arc[v][i] && visited[i] != 1) - DFS(G, i); -} - -void BFS(Graph *G, int v) -{ - int f; - queue q; - if(!visited[v]) - { - cout << G->vertex[v]; - visited[v] = 1; - q.push(v); - } - while(!q.empty()) - { - f = q.front(); - q.pop(); - for(int i = 0; i < vnum; i++) - if(G->arc[f][i] && visited[i] != 1) - { - cout << G->vertex[i]; - visited[i] = 1; - q.push(i); - } - } -} - -int main() -{ - Graph *G = new Graph; - - int data[vnum] = {1, 2, 3, 4, 5}; - int arcMatrix[vnum][vnum] = - { - {0, 1, 1, 0, 0}, - {1, 0, 0, 1, 0}, - {1, 0, 0, 1, 1}, - {0, 1, 1, 0, 1}, - {0, 0, 1, 1, 0}, - }; - - CreatGraph(*G, data, arcMatrix); - cout << "vertex: "; - for(int i = 0; i < vnum; i++) - cout << G->vertex[i]; - cout << endl << "arc: " << endl; - for(int i = 0; i < vnum; i++) - { - cout << " "; - for(int j = 0; j < vnum; j++) - cout << G->arc[i][j]; - cout << endl; - } - cout << endl; - - cout << "DFS: " << endl; - DFS(G, 0); - cout << endl; - - memset(visited, 0, sizeof(visited)); - - cout << "BFS: " << endl; - BFS(G, 0); - cout << endl; - - return 0; -} From 270fb5470aca1b9ece5d86d163471e26da8236f8 Mon Sep 17 00:00:00 2001 From: Ranger Date: Sat, 15 Aug 2015 20:34:50 +0800 Subject: [PATCH 02/57] Single Number --- 136.txt | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 136.txt diff --git a/136.txt b/136.txt new file mode 100644 index 0000000..e16d7b7 --- /dev/null +++ b/136.txt @@ -0,0 +1,13 @@ +//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? + +class Solution { +public: + int singleNumber(vector& nums) { + for(int i = 1; i < nums.size(); i++) + nums[0] = nums[0] ^ nums[i]; + return nums[0]; + } +}; \ No newline at end of file From eac288b4c3c2baf948bb2bffcda4817356924afb Mon Sep 17 00:00:00 2001 From: Ranger Date: Sat, 15 Aug 2015 20:37:58 +0800 Subject: [PATCH 03/57] add explanation --- 136.txt | 1 + 1 file changed, 1 insertion(+) diff --git a/136.txt b/136.txt index e16d7b7..2ae00ce 100644 --- a/136.txt +++ b/136.txt @@ -3,6 +3,7 @@ //Note: //Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory? +// A ^ A = 0, 0 ^ A = 0, A ^ B ^ A = B class Solution { public: int singleNumber(vector& nums) { From 7746dcb2c7ce77f255ea0f560c32d2b93b0f20af Mon Sep 17 00:00:00 2001 From: Ranger Date: Sat, 15 Aug 2015 21:09:09 +0800 Subject: [PATCH 04/57] Delete Node in a Linked List --- 237.txt | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 237.txt diff --git a/237.txt b/237.txt new file mode 100644 index 0000000..36a98bc --- /dev/null +++ b/237.txt @@ -0,0 +1,23 @@ +//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) {} + * }; + */ + + // can't get the head node, so implemented by deleting the next node +class Solution { +public: + void deleteNode(ListNode* node) { + //node->val = node->next->val; + //node->next = node->next->next; + auto d_node = node->next; + *node = *node->next; + delete d_node; + } +}; \ No newline at end of file From 348657fa1c674d1f9336aea0881c9d3f31e543d1 Mon Sep 17 00:00:00 2001 From: Ranger Date: Sat, 15 Aug 2015 22:46:10 +0800 Subject: [PATCH 05/57] Same Tree --- 100.txt | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 100.txt diff --git a/100.txt b/100.txt new file mode 100644 index 0000000..e699c40 --- /dev/null +++ b/100.txt @@ -0,0 +1,25 @@ +/** + * 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: + bool isSameTree(TreeNode* p, TreeNode* q) { + //check the node itself + if(p==NULL && q==NULL) return true; + else + if(p==NULL||q==NULL) return false; + else + { + if(p->val != q->val) return false; + else + //check the child nodes + isSameTree(p->left, q->left) && isSameTree(p->right, q->right); + } + } +}; \ No newline at end of file From cd71e2870ec944ebabe52a5f5a22cf975e51674b Mon Sep 17 00:00:00 2001 From: Ranger Date: Sun, 16 Aug 2015 15:47:22 +0800 Subject: [PATCH 06/57] Add Digits --- 258.txt | 48 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 258.txt diff --git a/258.txt b/258.txt new file mode 100644 index 0000000..73cfd02 --- /dev/null +++ b/258.txt @@ -0,0 +1,48 @@ +//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? +//Hint: +// A naive implementation of the above process is trivial. Could you come up with other methods? +// What are all the possible results? +// How do they occur, periodically or randomly? + +// not the best one +class Solution { +public: + int addDigits(int num) { + if(num < 10) return num; + while(num >= 10) + num = num/10 + num % 10; + return num; + } +}; + +/* +The problem, widely known as digit root problem, has a congruence formula: +https://en.wikipedia.org/wiki/Digital_root#Congruence_formula + +For base b (decimal case b = 10), the digit root of an integer is: + dr(n) = 0 if n == 0 + dr(n) = (b-1) if n != 0 and n % (b-1) == 0 + dr(n) = n mod (b-1) if n % (b-1) != 0 +or + dr(n) = 1 + (n - 1) % 9 + +Note here, when n = 0, since (n - 1) % 9 = -1, the return value is zero (correct). +From the formula, we can find that the result of this problem is immanently periodic, with period (b-1). +Output sequence for decimals (b = 10): + +~input: 0 1 2 3 4 ... +output: 0 1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8 9 1 2 3 .... + +Henceforth, we can write the following code, whose time and space complexities are both O(1). +*/ + +class Solution { +public: + int addDigits(int num) { + return 1 + (num - 1) % 9; + } +}; \ No newline at end of file From faf239fd6ecf30fe7bafcc771a44cb4857468718 Mon Sep 17 00:00:00 2001 From: Ranger Date: Sun, 16 Aug 2015 16:13:34 +0800 Subject: [PATCH 07/57] Number of 1 Bits --- 191.txt | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 191.txt diff --git a/191.txt b/191.txt new file mode 100644 index 0000000..c0b2f07 --- /dev/null +++ b/191.txt @@ -0,0 +1,15 @@ +//Write a function that takes an unsigned integer and returns the number of '1' bits it has (also known as the Hamming weight). +//For example, the 32-bit integer '11' has binary representation 00000000000000000000000000001011, so the function should return 3. + +class Solution { +public: + int hammingWeight(uint32_t n) { + int num = 0; + while(n) + { + n = n & (n-1); + num++; + } + return num; + } +}; \ No newline at end of file From 399f77d6dc91a53521a027e1afb1f2af8a703191 Mon Sep 17 00:00:00 2001 From: Ranger Date: Sun, 16 Aug 2015 17:27:30 +0800 Subject: [PATCH 08/57] Lowest Common Ancestor of a Binary Search Tree --- 235.txt | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 235.txt diff --git a/235.txt b/235.txt new file mode 100644 index 0000000..7a1167d --- /dev/null +++ b/235.txt @@ -0,0 +1,33 @@ +//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. + +/** + * 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) { + if(p->val == root->val || q->val == root->val + || (p->val < root->val && q->val > root->val) || (p->val > root->val && q->val < root->val)) + return root; + else + { + if(p->val < root->val && q->val < root->val) return lowestCommonAncestor(root->left, p, q); + if(p->val > root->val && q->val > root->val) return lowestCommonAncestor(root->right, p, q); + } + } +}; \ No newline at end of file From d1e29c25a3e2d63973434c882cf44c562930649d Mon Sep 17 00:00:00 2001 From: Ranger Date: Sun, 16 Aug 2015 17:28:23 +0800 Subject: [PATCH 09/57] modified --- 235.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/235.txt b/235.txt index 7a1167d..4dfe498 100644 --- a/235.txt +++ b/235.txt @@ -1,5 +1,5 @@ //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).¡± +//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__ From fdd9e5deb016c640ee886a3e0e04ea229babf0db Mon Sep 17 00:00:00 2001 From: Ranger Date: Sun, 16 Aug 2015 18:10:28 +0800 Subject: [PATCH 10/57] Invert Binary Tree --- 226.txt | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 226.txt diff --git a/226.txt b/226.txt new file mode 100644 index 0000000..3a7011d --- /dev/null +++ b/226.txt @@ -0,0 +1,39 @@ +Invert a binary tree. + + 4 + / \ + 2 7 + / \ / \ +1 3 6 9 + +to + + 4 + / \ + 7 2 + / \ / \ +9 6 3 1 + + +/** + * 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* invertTree(TreeNode* root) { + if(root == NULL) return NULL; + else + { + swap(root->left, root->right); + invertTree(root->left); + invertTree(root->right); + } + return root; + } +}; \ No newline at end of file From 5d33400132a7ff12c238301e61553357cd8c55f8 Mon Sep 17 00:00:00 2001 From: Ranger Date: Sun, 16 Aug 2015 21:48:53 +0800 Subject: [PATCH 11/57] modified the implementation of invert binary tree --- 226.txt | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/226.txt b/226.txt index 3a7011d..5f47b50 100644 --- a/226.txt +++ b/226.txt @@ -27,13 +27,12 @@ to class Solution { public: TreeNode* invertTree(TreeNode* root) { - if(root == NULL) return NULL; - else + if(root) { swap(root->left, root->right); invertTree(root->left); invertTree(root->right); - } - return root; + } + return root; } }; \ No newline at end of file From 8d958ac172184df77e9c00c9f644b31dcf953cbb Mon Sep 17 00:00:00 2001 From: Ranger Date: Sun, 16 Aug 2015 22:45:53 +0800 Subject: [PATCH 12/57] Excel Sheet Column Number --- 171.txt | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 171.txt diff --git a/171.txt b/171.txt new file mode 100644 index 0000000..f7381a9 --- /dev/null +++ b/171.txt @@ -0,0 +1,24 @@ +Related to question Excel Sheet Column Title +Given a column title as appear in an Excel sheet, return its corresponding column number. +For example: + A -> 1 + B -> 2 + C -> 3 + ... + Z -> 26 + AA -> 27 + AB -> 28 + + +class Solution { +public: + int titleToNumber(string s) { + int j = 0,n = 0; + for(int i = 0; i < s.size() ; i++) + { + j = s.size() - 1 - i; + n = n + pow(26, i) * (s[j] - 'A' + 1); + } + return n; + } +}; \ No newline at end of file From 2198b953f3a875fee1a224a128021ecbd182fbbb Mon Sep 17 00:00:00 2001 From: Ranger Date: Mon, 17 Aug 2015 15:46:02 +0800 Subject: [PATCH 13/57] Excel Sheet Column Title --- 168.txt | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 168.txt diff --git a/168.txt b/168.txt new file mode 100644 index 0000000..5b2fe79 --- /dev/null +++ b/168.txt @@ -0,0 +1,38 @@ +Given a positive integer, return its corresponding column title as appear in an Excel sheet. +For example: + + 1 -> A + 2 -> B + 3 -> C + ... + 26 -> Z + 27 -> AA + 28 -> AB + + +class Solution { +public: + string convertToTitle(int n) { + string result, s_tmp; + char ch_tmp; + int tail = 0; + while(n > 0) + { + tail = n % 26; + if(tail == 0) + { + tail = 26; + result = "Z" + result; + } + else + { + ch_tmp = 'A' - 1 + tail; + s_tmp = ch_tmp; + result = s_tmp + result; + } + n = (n - tail)/26; + } + + return result; + } +}; \ No newline at end of file From ebb936073f03d2cab03896aefb41e0643c1a8543 Mon Sep 17 00:00:00 2001 From: Ranger Date: Mon, 17 Aug 2015 15:50:15 +0800 Subject: [PATCH 14/57] add another method --- 168.txt | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/168.txt b/168.txt index 5b2fe79..b2ff879 100644 --- a/168.txt +++ b/168.txt @@ -32,6 +32,15 @@ public: } n = (n - tail)/26; } + + /* + while(n){ + n -= 1; + ch_tmp = 'A' + n % 26; + result = ch_tmp + result; + n /= 26; + } + */ return result; } From aad90f4be58a018506daf18901496c505ac69491 Mon Sep 17 00:00:00 2001 From: Ranger Date: Mon, 17 Aug 2015 20:55:45 +0800 Subject: [PATCH 15/57] Contains Duplicate --- 217.txt | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 217.txt diff --git a/217.txt b/217.txt new file mode 100644 index 0000000..c0884be --- /dev/null +++ b/217.txt @@ -0,0 +1,31 @@ +Given an array of integers, find if the array contains any duplicates. Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct. + +//sort and compare, faster +class Solution { +public: + bool containsDuplicate(vector& nums) { + sort(nums.begin(), nums.end()); + for(int i = 1; i < nums.size(); i++) + if(nums[i-1] == nums[i]) + return true; + return false; + } +}; + + +//use hash_set, slower +class Solution { +public: + bool containsDuplicate(vector& nums) { + unordered_set hash; + vector::iterator it = nums.begin(); + for(; it != nums.end(); it++) + { + if(hash.find(*it) != hash.end()) + return true; + else + hash.insert(*it); + } + return false; + } +}; \ No newline at end of file From 3aae58d445457d8e0ceb30c83a0f9b2f8efadf07 Mon Sep 17 00:00:00 2001 From: Ranger Date: Mon, 17 Aug 2015 22:24:23 +0800 Subject: [PATCH 16/57] Majority Element --- 169.txt | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 169.txt diff --git a/169.txt b/169.txt new file mode 100644 index 0000000..4337795 --- /dev/null +++ b/169.txt @@ -0,0 +1,36 @@ +Given an array of size n, find the majority element. The majority element is the element that appears more than ? n/2 ? times. + +You may assume that the array is non-empty and the majority element always exist in the array. + + +// sort then count +class Solution { +public: + int majorityElement(vector& nums) { + int n = 1; + if(nums.size() == 1) return nums[0]; + sort(nums.begin(),nums.end()); + for(int i = 1; i < nums.size(); i++) + if(nums[i - 1] == nums[i]) + { + n++; + if(n > nums.size()/2) return nums[i]; + } + } +}; + +// use hash map +class Solution { +public: + int majorityElement(vector& nums) { + unordered_map count; + for(int i = 0; i < nums.size(); i++) + { + if(++count[nums[i]] > nums.size()/2) + return nums[i]; + } + } +}; + +//6 Suggested Solutions in C++ with Explanations: +//https://leetcode.com/discuss/42929/6-suggested-solutions-in-c-with-explanations \ No newline at end of file From 29fc98208697b7c56e244188c96bd168a11a7edc Mon Sep 17 00:00:00 2001 From: Ranger Date: Mon, 17 Aug 2015 22:55:55 +0800 Subject: [PATCH 17/57] Remove Duplicates from Sorted List --- 83.txt | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 83.txt diff --git a/83.txt b/83.txt new file mode 100644 index 0000000..ad9bc4e --- /dev/null +++ b/83.txt @@ -0,0 +1,31 @@ +Given a sorted linked list, delete all duplicates such that each element appear only once. +For example, +Given 1->1->2, return 1->2. +Given 1->1->2->3->3, return 1->2->3. + +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode(int x) : val(x), next(NULL) {} + * }; + */ +class Solution { +public: + ListNode* deleteDuplicates(ListNode* head) { + ListNode *cur = head; + if(cur != NULL) + { + while(cur != NULL && cur->next != NULL) + { + if(cur->val == cur->next->val) + cur->next = cur->next->next; + else + cur = cur->next; + } + return head; + } + return head; + } +}; \ No newline at end of file From 56b92b5ea7b95e805cb7365b93e8a29627069a08 Mon Sep 17 00:00:00 2001 From: Ranger Date: Tue, 18 Aug 2015 13:56:17 +0800 Subject: [PATCH 18/57] Climbing Stairs --- 70.txt | 22 ++++++++++++++++++++++ 83.txt | 2 +- 2 files changed, 23 insertions(+), 1 deletion(-) create mode 100644 70.txt diff --git a/70.txt b/70.txt new file mode 100644 index 0000000..5f0b5c7 --- /dev/null +++ b/70.txt @@ -0,0 +1,22 @@ +You are climbing a stair case. It takes n steps to reach to the top. + +Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? + +// a Fibonacci problem, n1 means take 1 step and n2 means take 2 step +// F(n) = F(n - 1) + F(n - 2) +class Solution { +public: + int climbStairs(int n) { + if(n <= 0) return 0; + if(n == 1) return 1; + if(n == 2) return 2; + int n1 = 1, n2 = 2, count = 0; + for(int i = 2; i < n; i++) + { + count = n1 + n2; + n1 = n2; + n2 = count; + } + return count; + } +}; \ No newline at end of file diff --git a/83.txt b/83.txt index ad9bc4e..8121f2b 100644 --- a/83.txt +++ b/83.txt @@ -17,7 +17,7 @@ public: ListNode *cur = head; if(cur != NULL) { - while(cur != NULL && cur->next != NULL) + while(cur->next != NULL) { if(cur->val == cur->next->val) cur->next = cur->next->next; From 0e84dc078ecd5dbba86d7b31c9e74047e1da3ef7 Mon Sep 17 00:00:00 2001 From: Ranger Date: Tue, 18 Aug 2015 16:14:10 +0800 Subject: [PATCH 19/57] Roman to Integer --- 13.txt | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 13.txt diff --git a/13.txt b/13.txt new file mode 100644 index 0000000..248709c --- /dev/null +++ b/13.txt @@ -0,0 +1,33 @@ +Given a roman numeral, convert it to an integer. + +Input is guaranteed to be within the range from 1 to 3999. + +// the Roman alphabet is listed in the switch statement below +class Solution { +public: + int decode(char c){ + switch(c){ + case 'I': return 1; + case 'V': return 5; + case 'X': return 10; + case 'L': return 50; + case 'C': return 100; + case 'D': return 500; + case 'M': return 1000; + } + } + + int romanToInt(string s) { + int n = 0; + int n1, n2; + for(int i = 0; i < s.size() - 1; i++) + { + n1 = decode(s[i]); + n2 = decode(s[i + 1]); + if(n1 < n2) n -= n1; + else n += n1; + } + n += decode(s[s.size()-1]); + return n; + } +}; \ No newline at end of file From d248a3c21fb136c326ab7065729aa668d8a78ce8 Mon Sep 17 00:00:00 2001 From: Ranger Date: Tue, 18 Aug 2015 19:29:33 +0800 Subject: [PATCH 20/57] Valid Anagram --- 242.txt | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 242.txt diff --git a/242.txt b/242.txt new file mode 100644 index 0000000..56d9a25 --- /dev/null +++ b/242.txt @@ -0,0 +1,18 @@ +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. + +class Solution { +public: + bool isAnagram(string s, string t) { + unordered_map hash_s, hash_t; + for(int i = 0; i < s.size(); i++) + hash_s[s[i]]++; + for(int i = 0; i < t.size(); i++) + hash_t[t[i]]++; + return hash_s == hash_t; + } +}; \ No newline at end of file From d2508474e9c0a867aac6606a53db5c36cd03e6fb Mon Sep 17 00:00:00 2001 From: Ranger Date: Tue, 18 Aug 2015 19:53:41 +0800 Subject: [PATCH 21/57] Implement Queue using Stacks --- 232.txt | 64 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 64 insertions(+) create mode 100644 232.txt diff --git a/232.txt b/232.txt new file mode 100644 index 0000000..41723cb --- /dev/null +++ b/232.txt @@ -0,0 +1,64 @@ +Implement the following operations of a queue using stacks. + + push(x) -- Push element x to the back of queue. + pop() -- Removes the element from in front of queue. + peek() -- Get the front element. + empty() -- Return whether the queue is empty. + +Notes: + + You must use only standard operations of a stack -- which means only push to top, peek/pop from top, size, and is empty operations are valid. + Depending on your language, stack may not be supported natively. You may simulate a stack by using a list or deque (double-ended queue), as long as you use only standard operations of a stack. + You may assume that all operations are valid (for example, no pop or peek operations will be called on an empty queue). + + +class Queue { + stack stack1, stack2; +public: + // Push element x to the back of queue. + void push(int x) { + stack1.push(x); + } + + // Removes the element from in front of queue. + void pop(void) { + int n; + while(!stack1.empty()) + { + n = stack1.top(); + stack1.pop(); + stack2.push(n); + } + stack2.pop(); + while(!stack2.empty()) + { + n = stack2.top(); + stack2.pop(); + stack1.push(n); + } + } + + // Get the front element. + int peek(void) { + int m,n; + while(!stack1.empty()) + { + n = stack1.top(); + stack1.pop(); + stack2.push(n); + } + m = stack2.top(); + while(!stack2.empty()) + { + n = stack2.top(); + stack2.pop(); + stack1.push(n); + } + return m; + } + + // Return whether the queue is empty. + bool empty(void) { + return stack1.empty() && stack2.empty(); + } +}; \ No newline at end of file From ef507cfed5b58fde83f0e57ce8b4d684ee321e77 Mon Sep 17 00:00:00 2001 From: Ranger Date: Tue, 18 Aug 2015 20:46:36 +0800 Subject: [PATCH 22/57] Merge Two Sorted Lists --- 21.txt | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 21.txt diff --git a/21.txt b/21.txt new file mode 100644 index 0000000..eeca56b --- /dev/null +++ b/21.txt @@ -0,0 +1,33 @@ +Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists. + +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode(int x) : val(x), next(NULL) {} + * }; + */ +class Solution { +public: + ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { + if(l1 == NULL) return l2; + if(l2 == NULL) return l1; + + ListNode *result; + if(l1->val <= l2->val) { result = l1; l1 = l1->next; } + else { result = l2; l2 = l2->next; } + + ListNode *p = result; + while(l1 != NULL && l2 != NULL) + { + if(l1->val <= l2->val) { p->next = l1; l1 = l1->next; } + else { p->next = l2; l2 = l2->next; } + p = p->next; + } + if(l1 != NULL && l2 == NULL) { p->next = l1; } + if(l2 != NULL && l1 == NULL) { p->next = l2; } + + return result; + } +}; \ No newline at end of file From ddbacc71b99a58b6277ac8572e8a8744316e4022 Mon Sep 17 00:00:00 2001 From: Ranger Date: Tue, 18 Aug 2015 21:16:38 +0800 Subject: [PATCH 23/57] Reverse Linked List --- 206.txt | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 206.txt diff --git a/206.txt b/206.txt new file mode 100644 index 0000000..a620917 --- /dev/null +++ b/206.txt @@ -0,0 +1,33 @@ +Reverse a singly linked list. + +click to show more hints. +Hint: +A linked list can be reversed either iteratively or recursively. Could you implement both? + + +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode(int x) : val(x), next(NULL) {} + * }; + */ +class Solution { +public: + ListNode* reverseList(ListNode* head) { + if(head == NULL || head->next == NULL) return head; + ListNode *p, *pre; + pre = NULL; + while(head->next != NULL) + { + p = head; + head = head->next; + p->next = pre; + pre = p; + } + head->next = p; + + return head; + } +}; \ No newline at end of file From f7335884511d1681ef84c9f73c2e8b5b3af6a386 Mon Sep 17 00:00:00 2001 From: Ranger Date: Tue, 18 Aug 2015 23:00:05 +0800 Subject: [PATCH 24/57] Happy Number --- 202.txt | 57 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 202.txt diff --git a/202.txt b/202.txt new file mode 100644 index 0000000..cf827b6 --- /dev/null +++ b/202.txt @@ -0,0 +1,57 @@ +Write an algorithm to determine if a number is "happy". + +A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers. + +Example: 19 is a happy number + + 12 + 92 = 82 + 82 + 22 = 68 + 62 + 82 = 100 + 12 + 02 + 02 = 1 + +// if the number is not happy,it loops as 4->16->37->58->89->145->42->20->4, +// so we can use a fast and a slow pointer to test if there is a cycle +class Solution { +public: + int digitSquareSum(int n) + { + int sum = 0, tmp; + while(n) + { + tmp = n % 10; + sum += tmp * tmp; + n /= 10; + } + return sum; + } + bool isHappy(int n) { + int slow, fast; + slow = fast = n; + do { + slow = digitSquareSum(slow); + fast = digitSquareSum(digitSquareSum(fast)); + } while(slow != fast); + + if(slow == 1) return true; + else return false; + } +}; + +// now that 4 is unhappy, we have follow code +class Solution { +public: + bool isHappy(int n) { + while (true) { + if (n == 1) { return true; } + if (n == 4) { return false; } + int sum = 0, tmp; + while (n) + { + tmp = n % 10; + sum += tmp * tmp; + n /= 10; + } + n = next; + } + } +}; \ No newline at end of file From f3f924f48ec8eba0a2d203ffd2dbd96fa9a3a30f Mon Sep 17 00:00:00 2001 From: Ranger Date: Wed, 19 Aug 2015 12:28:32 +0800 Subject: [PATCH 25/57] Ugly Number --- 110.txt | 49 +++++++++++++++++++++++++++++++++++++++++++++++++ 263.txt | 17 +++++++++++++++++ 2 files changed, 66 insertions(+) create mode 100644 110.txt create mode 100644 263.txt diff --git a/110.txt b/110.txt new file mode 100644 index 0000000..946e0ce --- /dev/null +++ b/110.txt @@ -0,0 +1,49 @@ +Given a binary tree, determine if it is height-balanced. +For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1. + +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} + * }; + */ +// top to down +class Solution { +public: + int depth(TreeNode* root){ + if(root == NULL) + return 0; + else + return max(depth(root->left), depth(root->right)) + 1; + } + bool isBalanced(TreeNode* root) { + if(root == NULL) return true; + int ld = depth(root->left); + int rd = depth(root->right); + if(abs(ld-rd) > 1) + return false; + else + return isBalanced(root->left) && isBalanced(root->right); + } +}; + +// bottom up +class Solution { +public: + //if not balance ,return -1; else return the depth + int balanceness(TreeNode* root){ + if(root == NULL) return 0; + int ld = balanceness(root->left); + if(ld == -1) return -1; + int rd = balanceness(root->right); + if(rd == -1) return -1; + if(abs(ld - rd) > 1) return -1; + return max(ld, rd) + 1; + } + bool isBalanced(TreeNode* root) { + return balanceness(root) != -1; + } +}; \ No newline at end of file diff --git a/263.txt b/263.txt new file mode 100644 index 0000000..a713737 --- /dev/null +++ b/263.txt @@ -0,0 +1,17 @@ +Write a program to check whether a given number is an ugly number. + +Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. For example, 6, 8 are ugly while 14 is not ugly since it includes another prime factor 7. + +Note that 1 is typically treated as an ugly number. + +class Solution { +public: + bool isUgly(int num) { + if(num <= 0) return false; + if(num == 1) return true; + while(num % 2 == 0) num /= 2; + while(num % 3 == 0) num /= 3; + while(num % 5 == 0) num /= 5; + return num == 1; + } +}; \ No newline at end of file From 0996c3e8e7d4c456b48ae3637e4e2ef69bc2bf93 Mon Sep 17 00:00:00 2001 From: Ranger Date: Wed, 19 Aug 2015 12:29:32 +0800 Subject: [PATCH 26/57] Balanced Binary Tree --- 110.txt | 1 + 1 file changed, 1 insertion(+) diff --git a/110.txt b/110.txt index 946e0ce..7fdda81 100644 --- a/110.txt +++ b/110.txt @@ -10,6 +10,7 @@ For this problem, a height-balanced binary tree is defined as a binary tree in w * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ + // top to down class Solution { public: From da10a74c18ca48d05d85c315b7d9384fc464ba0d Mon Sep 17 00:00:00 2001 From: Ranger Date: Wed, 19 Aug 2015 16:32:36 +0800 Subject: [PATCH 27/57] Remove Element --- 27.txt | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 27.txt diff --git a/27.txt b/27.txt new file mode 100644 index 0000000..ce690ef --- /dev/null +++ b/27.txt @@ -0,0 +1,33 @@ +Given an array and a value, remove all instances of that value in place and return the new length. + +The order of elements can be changed. It doesn't matter what you leave beyond the new length. + +// use "erase" +class Solution { +public: + int removeElement(vector& nums, int val) { + vector::iterator it; + for(it = nums.begin(); it != nums.end();) + if(*it == val) + it = nums.erase(it); + else it++; + return nums.size(); + } +}; + +// use the last element to cover the value +class Solution { +public: + int removeElement(vector& nums, int val) { + for(int i = 0; i < nums.size(); i++) + { + if(nums[i] == val) + { + nums[i] = nums[nums.size() - 1]; + nums.pop_back(); + i--; + } + } + return nums.size(); + } +}; \ No newline at end of file From babb64b5c409e1929bb02906731f99c9d7e7b678 Mon Sep 17 00:00:00 2001 From: Ranger Date: Wed, 19 Aug 2015 18:01:32 +0800 Subject: [PATCH 28/57] Symmetric Tree --- 101.txt | 95 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 95 insertions(+) create mode 100644 101.txt diff --git a/101.txt b/101.txt new file mode 100644 index 0000000..a9ef5e9 --- /dev/null +++ b/101.txt @@ -0,0 +1,95 @@ +Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center). + +For example, this binary tree is symmetric: + + 1 + / \ + 2 2 + / \ / \ +3 4 4 3 + +But the following is not: + + 1 + / \ + 2 2 + \ \ + 3 3 + +Note: +Bonus points if you could solve it both recursively and iteratively. + +confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ. + +OJ's Binary Tree Serialization: + +The serialization of a binary tree follows a level order traversal, where '#' signifies a path terminator where no node exists below. + +Here's an example: + + 1 + / \ + 2 3 + / + 4 + \ + 5 + +The above binary tree is serialized as "{1,2,3,#,#,4,#,#,5}". + +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} + * }; + */ +// use recursion +class Solution { +public: + bool DFS(TreeNode* left, TreeNode* right) + { + if(left == NULL && right == NULL) return true; + if(left == NULL || right == NULL) return false; + if(left->val != right->val) return false; + else + return DFS(left->left,right->right) && DFS(left->right, right->left); + } + bool isSymmetric(TreeNode* root) { + if(root == NULL) return true; + return DFS(root->left, root->right); + } +}; + +// use two queues to record the left and right branch +class Solution { +public: + bool isSymmetric(TreeNode* root) { + if(root == NULL) return true; + TreeNode *left, *right; + queue q1, q2; + q1.push(root->left); + q2.push(root->right); + while(!q1.empty() && !q2.empty()) + { + left = q1.front(); + q1.pop(); + right = q2.front(); + q2.pop(); + + if(left == NULL && right == NULL) continue; + if(left == NULL || right == NULL) return false; + if(left->val != right->val) return false; + else + { + q1.push(left->left); + q1.push(left->right); + q2.push(right->right); + q2.push(right->left); + } + } + return true; + } +}; \ No newline at end of file From a018254ffadc3a725c9bf6c2348e08978b938b25 Mon Sep 17 00:00:00 2001 From: Ranger Date: Wed, 19 Aug 2015 19:47:12 +0800 Subject: [PATCH 29/57] Remove Duplicates from Sorted Array --- 26.txt | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 26.txt diff --git a/26.txt b/26.txt new file mode 100644 index 0000000..ba82c7c --- /dev/null +++ b/26.txt @@ -0,0 +1,22 @@ +Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length. +Do not allocate extra space for another array, you must do this in place with constant memory. +For example, +Given input array nums = [1,1,2], +Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively. It doesn't matter what you leave beyond the new length. + +class Solution { +public: + int removeDuplicates(vector& nums) { + if(nums.size() < 2) return nums.size(); + int count = 1; + for(int i = 1; i < nums.size(); i++) + { + if(nums[i - 1] != nums[i]) + { + nums[count] = nums[i]; + count++; + } + } + return count; + } +}; \ No newline at end of file From ee3363e9a9c0d08dcfa9ca74de824f499501e59e Mon Sep 17 00:00:00 2001 From: Ranger Date: Wed, 19 Aug 2015 20:18:36 +0800 Subject: [PATCH 30/57] Implement Stack using Queues --- 225.txt | 47 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 225.txt diff --git a/225.txt b/225.txt new file mode 100644 index 0000000..84cc32d --- /dev/null +++ b/225.txt @@ -0,0 +1,47 @@ +Implement the following operations of a stack using queues. + + push(x) -- Push element x onto stack. + pop() -- Removes the element on top of the stack. + top() -- Get the top element. + empty() -- Return whether the stack is empty. + +Notes: + + You must use only standard operations of a queue -- which means only push to back, peek/pop from front, size, and is empty operations are valid. + Depending on your language, queue may not be supported natively. You may simulate a queue by using a list or deque (double-ended queue), as long as you use only standard operations of a queue. + You may assume that all operations are valid (for example, no pop or top operations will be called on an empty stack). + +// queue front is the stack top +class Stack { + queue q1, q2; +public: + // Push element x onto stack. + void push(int x) { + q2.push(x); + while(!q1.empty()) + { + q2.push(q1.front()); + q1.pop(); + } + while(!q2.empty()) + { + q1.push(q2.front()); + q2.pop(); + } + } + + // Removes the element on top of the stack. + void pop() { + q1.pop(); + } + + // Get the top element. + int top() { + return q1.front(); + } + + // Return whether the stack is empty. + bool empty() { + return q1.empty() && q2.empty(); + } +}; \ No newline at end of file From 94c061f174a39205b1d2e7e5b9c29e4568165295 Mon Sep 17 00:00:00 2001 From: Ranger Date: Wed, 19 Aug 2015 20:23:15 +0800 Subject: [PATCH 31/57] change to one queue --- 225.txt | 21 ++++++++------------- 1 file changed, 8 insertions(+), 13 deletions(-) diff --git a/225.txt b/225.txt index 84cc32d..b4dc827 100644 --- a/225.txt +++ b/225.txt @@ -13,35 +13,30 @@ Notes: // queue front is the stack top class Stack { - queue q1, q2; + queue q; public: // Push element x onto stack. void push(int x) { - q2.push(x); - while(!q1.empty()) + q.push(x); + for(int i = 0; i < q.size() -1; i++) { - q2.push(q1.front()); - q1.pop(); - } - while(!q2.empty()) - { - q1.push(q2.front()); - q2.pop(); + q.push(q.front()); + q.pop(); } } // Removes the element on top of the stack. void pop() { - q1.pop(); + q.pop(); } // Get the top element. int top() { - return q1.front(); + return q.front(); } // Return whether the stack is empty. bool empty() { - return q1.empty() && q2.empty(); + return q.empty(); } }; \ No newline at end of file From 2ea7cf40732e971f5fd99f716c6476682f08fac2 Mon Sep 17 00:00:00 2001 From: Ranger Date: Sun, 23 Aug 2015 16:29:17 +0800 Subject: [PATCH 32/57] Plus One --- 66.txt | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 66.txt diff --git a/66.txt b/66.txt new file mode 100644 index 0000000..0804496 --- /dev/null +++ b/66.txt @@ -0,0 +1,20 @@ +Given a non-negative number represented as an array of digits, plus one to the number. +The digits are stored such that the most significant digit is at the head of the list. + +class Solution { +public: + vector plusOne(vector& digits) { + int flag = 0; + for(int i = digits.size() - 1; i >=0; i--) + { + if(i == digits.size() -1) digits[i]++; + if(flag == 1) digits[i]++; + + flag = digits[i]/10; + digits[i] = digits[i] % 10; + } + if(flag == 1) + digits.insert(digits.begin(),1); + return digits; + } +}; \ No newline at end of file From 1f63ddbdfb13bccba6a13948322184f9d9d8be85 Mon Sep 17 00:00:00 2001 From: Ranger Date: Sun, 23 Aug 2015 17:34:29 +0800 Subject: [PATCH 33/57] Pascal's Triangle --- 118.txt | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 118.txt diff --git a/118.txt b/118.txt new file mode 100644 index 0000000..506f441 --- /dev/null +++ b/118.txt @@ -0,0 +1,32 @@ +Given numRows, generate the first numRows of Pascal's triangle. +For example, given numRows = 5, +Return +[ + [1], + [1,1], + [1,2,1], + [1,3,3,1], + [1,4,6,4,1] +] + +class Solution { +public: + vector> generate(int numRows) { + vector> pascal; + pascal.resize(numRows); + for(int i = 1; i <= numRows; i++) + pascal[i - 1].resize(i); + + for(int i = 0; i < numRows; i++) + for(int j = 0; j < i + 1; j++) + { + if(j == 0) pascal[i][j] = 1; + else + if(j == i) pascal[i][j] = 1; + else + pascal[i][j] = pascal[i - 1][j - 1] + pascal[i - 1][j]; + } + + return pascal; + } +}; \ No newline at end of file From 04c4ab311af4e31607bf6edaf97b2940bc98969b Mon Sep 17 00:00:00 2001 From: Ranger Date: Sun, 23 Aug 2015 19:14:42 +0800 Subject: [PATCH 34/57] Power of Two --- 231.txt | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 231.txt diff --git a/231.txt b/231.txt new file mode 100644 index 0000000..75732e9 --- /dev/null +++ b/231.txt @@ -0,0 +1,24 @@ +Given an integer, write a function to determine if it is a power of two. + +class Solution { +public: + bool isPowerOfTwo(int n) { + if(n <= 0) return false; + while(n) + { + if(n == 1) return true; + if(n % 2 != 0) return false; + + n = n/2; + } + } +}; + +// power of 2 means only have 1 bit of "1" +class Solution { +public: + bool isPowerOfTwo(int n) { + if(n <= 0) return false; + return !(n & (n - 1)); + } +}; \ No newline at end of file From 891c092bd4f6c9b1c6672f1434235558cde42133 Mon Sep 17 00:00:00 2001 From: Ranger Date: Sun, 23 Aug 2015 20:33:56 +0800 Subject: [PATCH 35/57] Path Sum --- 112.txt | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 112.txt diff --git a/112.txt b/112.txt new file mode 100644 index 0000000..c0c5bf2 --- /dev/null +++ b/112.txt @@ -0,0 +1,31 @@ +Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum. +For example: +Given the below binary tree and sum = 22, + + 5 + / \ + 4 8 + / / \ + 11 13 4 + / \ \ + 7 2 1 + +return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22. + +/** + * 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: + bool hasPathSum(TreeNode* root, int sum) { + if(root == NULL) return false; + if(root->left == NULL && root->right == NULL && sum == root->val) return true; + return hasPathSum(root->left, sum - root->val) || hasPathSum(root->right, sum - root->val); + } +}; \ No newline at end of file From 7cf2d0f0fd224817d6f425561475743b7f38c76a Mon Sep 17 00:00:00 2001 From: Ranger Date: Sun, 23 Aug 2015 22:05:33 +0800 Subject: [PATCH 36/57] Pascal's Triangle II --- 119.txt | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 119.txt diff --git a/119.txt b/119.txt new file mode 100644 index 0000000..67967bb --- /dev/null +++ b/119.txt @@ -0,0 +1,21 @@ +Given an index k, return the kth row of the Pascal's triangle. + +For example, given k = 3, +Return [1,3,3,1]. + +Note: +Could you optimize your algorithm to use only O(k) extra space? + +// use O(k) extra space +class Solution { +public: + vector getRow(int rowIndex) { + vector pascal(rowIndex + 1, 0); + pascal[0] = 1; + + for(int i = 1; i < rowIndex + 1; i++) + for(int j = i; j >= 1; j--) + pascal[j] += pascal[j - 1]; + return pascal; + } +}; \ No newline at end of file From 3ac7023702fcabab3f5ab8112065f70df0b1f2b8 Mon Sep 17 00:00:00 2001 From: Ranger Date: Mon, 24 Aug 2015 17:10:38 +0800 Subject: [PATCH 37/57] House Robber --- 198.txt | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 198.txt diff --git a/198.txt b/198.txt new file mode 100644 index 0000000..f84eca3 --- /dev/null +++ b/198.txt @@ -0,0 +1,36 @@ +You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security system connected and it will automatically contact the police if two adjacent houses were broken into on the same night. + +Given a list of non-negative integers representing the amount of money of each house, determine the maximum amount of money you can rob tonight without alerting the police. + +class Solution { +public: + int rob(vector& nums) { + int robber[nums.size() + 1][2] = {0}; + for(int i = 1; i <= nums.size(); i++) + { + robber[i][0] = max(robber[i - 1][0], robber[i - 1][1]); // if not rob + robber[i][1] = nums[i - 1] + robber[i - 1][0]; // if rob + } + + return max(robber[nums.size()][0], robber[nums.size()][1]); + } +}; + + +// O(1) space +class Solution { +public: + int rob(vector& nums) { + int rob = 0; + int notrob = 0; + int temp = 0; + for(int i = 0; i < nums.size(); i++) + { + temp = notrob; //temp is used to keep the unmodified notrob + notrob = max(rob, notrob); //if not rob, compare + rob = nums[i] + temp; //if rob, previous house must not rob + } + + return max(rob, notrob); + } +}; \ No newline at end of file From 61824e468b7cc86bdeb583ca96b9d6db6c9e02e4 Mon Sep 17 00:00:00 2001 From: Ranger Date: Sat, 29 Aug 2015 11:47:52 +0800 Subject: [PATCH 38/57] Factorial Trailing Zeroes --- 172.txt | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 172.txt diff --git a/172.txt b/172.txt new file mode 100644 index 0000000..c23609a --- /dev/null +++ b/172.txt @@ -0,0 +1,20 @@ +Given an integer n, return the number of trailing zeroes in n!. + +Note: Your solution should be in logarithmic time complexity. + +// count the number of 5 +class Solution { +public: + int trailingZeroes(int n) { + int count = 0; + int i = n; + + while(i > 1) + { + count += i/5; + i = i/5; + } + + return count; + } +}; \ No newline at end of file From 19b08fcbe994fb3dfa046e303761313aef63b5cf Mon Sep 17 00:00:00 2001 From: Ranger Date: Sat, 29 Aug 2015 20:11:57 +0800 Subject: [PATCH 39/57] 102 --- Binary Tree Level Order Traversal.txt | 37 +++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 Binary Tree Level Order Traversal.txt diff --git a/Binary Tree Level Order Traversal.txt b/Binary Tree Level Order Traversal.txt new file mode 100644 index 0000000..9963ca1 --- /dev/null +++ b/Binary Tree Level Order Traversal.txt @@ -0,0 +1,37 @@ +/** + * 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> levelOrder(TreeNode* root) { + if(!root) return {}; + vector> result; + vector row; + queue q; + q.push(root); + int count = 1; + + while(!q.empty()) + { + if(q.front()->left) q.push(q.front()->left); + if(q.front()->right) q.push(q.front()->right); + row.push_back(q.front()->val); + q.pop(); + count--; + if(count == 0) + { + result.push_back(row); + row.clear(); + count = q.size(); + } + } + + return result; + } +}; \ No newline at end of file From c2e38df5761474b13f160efda8329b47b5b3cbe1 Mon Sep 17 00:00:00 2001 From: Ranger Date: Sat, 29 Aug 2015 20:30:56 +0800 Subject: [PATCH 40/57] 107 --- Binary Tree Level Order Traversal.txt | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/Binary Tree Level Order Traversal.txt b/Binary Tree Level Order Traversal.txt index 9963ca1..9bc6aef 100644 --- a/Binary Tree Level Order Traversal.txt +++ b/Binary Tree Level Order Traversal.txt @@ -1,3 +1,23 @@ +Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level). + +For example: +Given binary tree {3,9,20,#,#,15,7}, + + 3 + / \ + 9 20 + / \ + 15 7 + +return its level order traversal as: + +[ + [3], + [9,20], + [15,7] +] + + /** * Definition for a binary tree node. * struct TreeNode { From 3088512df25225f3b11745426193d6965265eee1 Mon Sep 17 00:00:00 2001 From: Ranger Date: Fri, 4 Sep 2015 15:00:44 +0800 Subject: [PATCH 41/57] 107 --- Binary Tree Level Order Traversal II.txt | 58 ++++++++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 Binary Tree Level Order Traversal II.txt diff --git a/Binary Tree Level Order Traversal II.txt b/Binary Tree Level Order Traversal II.txt new file mode 100644 index 0000000..e966ae4 --- /dev/null +++ b/Binary Tree Level Order Traversal II.txt @@ -0,0 +1,58 @@ +Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left to right, level by level from leaf to root). + +For example: +Given binary tree {3,9,20,#,#,15,7}, + + 3 + / \ + 9 20 + / \ + 15 7 + +return its bottom-up level order traversal as: + +[ + [15,7], + [9,20], + [3] +] + + +/** + * 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> levelOrderBottom(TreeNode* root) { + if(!root) return {}; + + vector> result; + vector row; + queue q; + q.push(root); + int count = 1; + + while(!q.empty()) + { + if(q.front()->left != NULL) q.push(q.front()->left); + if(q.front()->right != NULL) q.push(q.front()->right); + row.push_back(q.front()->val); + q.pop(); + count--; + if(count == 0) + { + result.insert(result.begin(), row); + row.clear(); + count = q.size(); + } + } + + return result; + } +}; \ No newline at end of file From cb36fa31747be1a6f245c59c67207103110b3ced Mon Sep 17 00:00:00 2001 From: Ranger Date: Fri, 4 Sep 2015 15:02:12 +0800 Subject: [PATCH 42/57] 160 --- Intersection of Two Linked Lists.txt | 55 ++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 Intersection of Two Linked Lists.txt diff --git a/Intersection of Two Linked Lists.txt b/Intersection of Two Linked Lists.txt new file mode 100644 index 0000000..f6ea6d2 --- /dev/null +++ b/Intersection of Two Linked Lists.txt @@ -0,0 +1,55 @@ +Write a program to find the node at which the intersection of two singly linked lists begins. + +For example, the following two linked lists: + +A: a1 ¡ú a2 + ¨K + c1 ¡ú c2 ¡ú c3 + ¨J +B: b1 ¡ú b2 ¡ú b3 + +begin to intersect at node c1. + +Notes: + + If the two linked lists have no intersection at all, return null. + The linked lists must retain their original structure after the function returns. + You may assume there are no cycles anywhere in the entire linked structure. + Your code should preferably run in O(n) time and use only O(1) memory. + + +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode(int x) : val(x), next(NULL) {} + * }; + */ +class Solution { +public: + ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) { + if(headA == NULL || headB == NULL) return NULL; + + ListNode *pa = headA, *pb = headB; + int len_a = 0, len_b = 0; + int diff = 0; + while(pa){++len_a; pa = pa->next;} + while(pb){++len_b; pb = pb->next;} + diff = abs(len_a - len_b); + pa = headA; + pb = headB; + + while(pa && pb){ + if(len_a > len_b) + while(diff){--diff; pa = pa->next;} + else + while(diff){--diff; pb = pb->next;} + while(pa != pb){ + pa = pa->next; + pb = pb->next; + } + return pa; + } + } +}; \ No newline at end of file From fafb7feb0f432912ee1cea33830938f74cc57560 Mon Sep 17 00:00:00 2001 From: Ranger Date: Fri, 4 Sep 2015 15:02:50 +0800 Subject: [PATCH 43/57] 102 --- Binary Tree Level Order Traversal.txt | 1 - 1 file changed, 1 deletion(-) diff --git a/Binary Tree Level Order Traversal.txt b/Binary Tree Level Order Traversal.txt index 9bc6aef..0733eb7 100644 --- a/Binary Tree Level Order Traversal.txt +++ b/Binary Tree Level Order Traversal.txt @@ -1,5 +1,4 @@ Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level). - For example: Given binary tree {3,9,20,#,#,15,7}, From 353b037d2b147941a8fd6eaf994d99f07e98a815 Mon Sep 17 00:00:00 2001 From: Ranger Date: Fri, 4 Sep 2015 15:20:57 +0800 Subject: [PATCH 44/57] 88 --- Merge Sorted Array.txt | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 Merge Sorted Array.txt diff --git a/Merge Sorted Array.txt b/Merge Sorted Array.txt new file mode 100644 index 0000000..e227e54 --- /dev/null +++ b/Merge Sorted Array.txt @@ -0,0 +1,31 @@ +Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array. + +Note: +You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2. The number of elements initialized in nums1 and nums2 are m and n respectively. + +class Solution { +public: + void merge(vector& nums1, int m, vector& nums2, int n) { + vector result; + int i = 0, j = 0; + while(i < m && j < n){ + if(nums1[i] <= nums2[j]){ + result.push_back(nums1[i]); + ++i; + } + else{ + result.push_back(nums2[j]); + ++j; + } + } + + if(i < m) + for(; i < m; ++i) + result.push_back(nums1[i]); + if(j < n) + for(; j < n; ++j) + result.push_back(nums2[j]); + + nums1 = result; + } +}; \ No newline at end of file From 6e37c9fdf031a3eb89dfc4dea58088bd1f441db6 Mon Sep 17 00:00:00 2001 From: Ranger Date: Fri, 4 Sep 2015 16:27:10 +0800 Subject: [PATCH 45/57] 190 --- Reverse Bits.txt | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 Reverse Bits.txt diff --git a/Reverse Bits.txt b/Reverse Bits.txt new file mode 100644 index 0000000..1ae7bd8 --- /dev/null +++ b/Reverse Bits.txt @@ -0,0 +1,36 @@ +Reverse bits of a given 32 bits unsigned integer. + +For example, given input 43261596 (represented in binary as 00000010100101000001111010011100), return 964176192 (represented in binary as 00111001011110000010100101000000). + +Follow up: +If this function is called many times, how would you optimize it? + +Related problem: Reverse Integer + + +class Solution { +public: + uint32_t reverseBits(uint32_t n) { + uint32_t result = 0; + + for(int i = 0; i < 32; ++i){ + if((n & 0x80000000) == 0x80000000) + result += pow(2,i); + n = n << 1; + } + + return result; + } +}; + +class Solution { +public: + uint32_t reverseBits(uint32_t n) { + uint32_t result = 0; + + for(int i = 0; i < 32; ++i) + result = (result << 1) + (n >> i & 1); + + return result; + } +}; \ No newline at end of file From 6314e740c16128c89e675824a63c4c3850238bf7 Mon Sep 17 00:00:00 2001 From: Ranger Date: Sat, 5 Sep 2015 22:03:23 +0800 Subject: [PATCH 46/57] 111 --- Minimum Depth of Binary Tree.txt | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 Minimum Depth of Binary Tree.txt diff --git a/Minimum Depth of Binary Tree.txt b/Minimum Depth of Binary Tree.txt new file mode 100644 index 0000000..8bc01e0 --- /dev/null +++ b/Minimum Depth of Binary Tree.txt @@ -0,0 +1,22 @@ +Given a binary tree, find its minimum depth. + +The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node. + +/** + * 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 minDepth(TreeNode* root) { + if(root == NULL) return 0; + if(root->left == NULL) return 1 + minDepth(root->right); + if(root->right == NULL) return 1 + minDepth(root->left); + return 1 + min(minDepth(root->left), minDepth(root->right)); + } +}; \ No newline at end of file From bfa82a13d3b17c866b871a6207bb59eebd9353cd Mon Sep 17 00:00:00 2001 From: Ranger Date: Thu, 17 Sep 2015 16:42:51 +0800 Subject: [PATCH 47/57] 9 --- Palindrome Number.txt | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 Palindrome Number.txt diff --git a/Palindrome Number.txt b/Palindrome Number.txt new file mode 100644 index 0000000..1d49fbe --- /dev/null +++ b/Palindrome Number.txt @@ -0,0 +1,19 @@ +Determine whether an integer is a palindrome. Do this without extra space. + +class Solution { +public: + bool isPalindrome(int x) { + if(x < 0) return false; + int rev = 0; + int tmp = x; + while(x != 0) + { + rev = rev * 10 + x % 10; + x = x / 10; + } + if(rev == tmp) + return true; + else + return false; + } +}; \ No newline at end of file From 018d54c012571816c4626fd610711e2e9c2e184d Mon Sep 17 00:00:00 2001 From: Ranger Date: Tue, 29 Sep 2015 13:19:46 +0800 Subject: [PATCH 48/57] 283 --- Move Zeroes.txt | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 Move Zeroes.txt diff --git a/Move Zeroes.txt b/Move Zeroes.txt new file mode 100644 index 0000000..7eb9925 --- /dev/null +++ b/Move Zeroes.txt @@ -0,0 +1,36 @@ +Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements. + +For example, given nums = [0, 1, 0, 3, 12], after calling your function, nums should be [1, 3, 12, 0, 0]. + +Note: + + You must do this in-place without making a copy of the array. + Minimize the total number of operations. + +Credits: +Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases. + + +class Solution { +public: + void moveZeroes(vector& nums) { + int len = nums.size(); + if(len == 1) return; + int n = 0; + for(int i = 0; i < len; i++) + { + if(nums[i] != 0) + { + nums[n] = nums[i]; + n++; + } + } + int diff = len - n; + while(diff) + { + nums[n] = 0; + n++; + diff--; + } + } +}; \ No newline at end of file From 34f924431c7562e3dfa89dfa28627deb6e437062 Mon Sep 17 00:00:00 2001 From: Ranger Date: Tue, 29 Sep 2015 14:14:20 +0800 Subject: [PATCH 49/57] 58 --- Length of Last Word.txt | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 Length of Last Word.txt diff --git a/Length of Last Word.txt b/Length of Last Word.txt new file mode 100644 index 0000000..7d3d1a9 --- /dev/null +++ b/Length of Last Word.txt @@ -0,0 +1,28 @@ +Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word in the string. + +If the last word does not exist, return 0. + +Note: A word is defined as a character sequence consists of non-space characters only. + +For example, +Given s = "Hello World", +return 5. + + +class Solution { +public: + int lengthOfLastWord(string s) { + int len = s.size(); + if(len == 0) return 0; + int i = len - 1; + int n = 0; + while(s[i] == ' ') + i--; + while(s[i] != ' ' && i >= 0) + { + n++; + i--; + } + return n; + } +}; \ No newline at end of file From 6cbd45228a154b5095143ab28d2185a1b4cab6d4 Mon Sep 17 00:00:00 2001 From: Ranger Date: Tue, 29 Sep 2015 15:06:27 +0800 Subject: [PATCH 50/57] 19 --- Remove Nth Node From End of List.txt | 49 ++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 Remove Nth Node From End of List.txt diff --git a/Remove Nth Node From End of List.txt b/Remove Nth Node From End of List.txt new file mode 100644 index 0000000..fd6ded1 --- /dev/null +++ b/Remove Nth Node From End of List.txt @@ -0,0 +1,49 @@ +Given a linked list, remove the nth node from the end of list and return its head. + +For example, + + Given linked list: 1->2->3->4->5, and n = 2. + + After removing the second node from the end, the linked list becomes 1->2->3->5. + +Note: +Given n will always be valid. +Try to do this in one pass. + + +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode(int x) : val(x), next(NULL) {} + * }; + */ +class Solution { +public: + ListNode* removeNthFromEnd(ListNode* head, int n) { + ListNode *newhead = new ListNode(0); + newhead->next = head; + ListNode *fast, *slow; + fast = newhead; + slow = newhead; + + while(n) + { + fast = fast->next; + n--; + } + + while(fast->next != nullptr) + { + fast = fast->next; + slow = slow->next; + } + + ListNode *tmp = slow->next; + slow->next = tmp->next; + tmp = nullptr; + + return newhead->next; + } +}; \ No newline at end of file From 8f29c3eadb945b150ebd03c29f1233af9c734a7c Mon Sep 17 00:00:00 2001 From: Ranger Date: Fri, 2 Oct 2015 21:11:45 +0800 Subject: [PATCH 51/57] 219 --- Contains Duplicate II.txt | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 Contains Duplicate II.txt diff --git a/Contains Duplicate II.txt b/Contains Duplicate II.txt new file mode 100644 index 0000000..ca1571d --- /dev/null +++ b/Contains Duplicate II.txt @@ -0,0 +1,16 @@ +Given an array of integers and an integer k, find out whether there are two distinct indices i and j in the array such that nums[i] = nums[j] and the difference between i and j is at most k. + +class Solution { +public: + bool containsNearbyDuplicate(vector& nums, int k) { + unordered_map hash_map; + for(int i = 0; i < nums.size(); i++) + { + if(hash_map.find(nums[i]) != hash_map.end() && (i - hash_map[nums[i]]) <= k) + return true; + else + hash_map[nums[i]] = i; + } + return false; + } +}; \ No newline at end of file From c9fa006edd589be61ebae07bd5af785948764c69 Mon Sep 17 00:00:00 2001 From: Ranger Date: Fri, 2 Oct 2015 21:18:25 +0800 Subject: [PATCH 52/57] add hash set --- Contains Duplicate II.txt | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/Contains Duplicate II.txt b/Contains Duplicate II.txt index ca1571d..94db1a5 100644 --- a/Contains Duplicate II.txt +++ b/Contains Duplicate II.txt @@ -1,5 +1,6 @@ Given an array of integers and an integer k, find out whether there are two distinct indices i and j in the array such that nums[i] = nums[j] and the difference between i and j is at most k. +// unordered_map class Solution { public: bool containsNearbyDuplicate(vector& nums, int k) { @@ -13,4 +14,25 @@ public: } return false; } +}; + +// unordered_set and sliding window +class Solution { +public: + bool containsNearbyDuplicate(vector& nums, int k) + { + unordered_set s; + + if (k <= 0) return false; + if (k >= nums.size()) k = nums.size() - 1; + + for (int i = 0; i < nums.size(); i++) + { + if (i > k) s.erase(nums[i - k - 1]); + if (s.find(nums[i]) != s.end()) return true; + s.insert(nums[i]); + } + + return false; + } }; \ No newline at end of file From f2b9be540b6f01071df89cec30ad96f3ba4fcf59 Mon Sep 17 00:00:00 2001 From: Ranger Date: Fri, 9 Oct 2015 22:19:18 +0800 Subject: [PATCH 53/57] 206 --- 206.txt => Reverse Linked List.txt | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename 206.txt => Reverse Linked List.txt (100%) diff --git a/206.txt b/Reverse Linked List.txt similarity index 100% rename from 206.txt rename to Reverse Linked List.txt From 2c9e73673769e2228041941ebd5435e26b2e8346 Mon Sep 17 00:00:00 2001 From: Ranger Date: Wed, 14 Oct 2015 11:22:09 +0800 Subject: [PATCH 54/57] 203 --- Remove Linked List Elements.txt | 39 +++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 Remove Linked List Elements.txt diff --git a/Remove Linked List Elements.txt b/Remove Linked List Elements.txt new file mode 100644 index 0000000..12e95c3 --- /dev/null +++ b/Remove Linked List Elements.txt @@ -0,0 +1,39 @@ +Remove all elements from a linked list of integers that have value val. + +Example +Given: 1 --> 2 --> 6 --> 3 --> 4 --> 5 --> 6, val = 6 +Return: 1 --> 2 --> 3 --> 4 --> 5 + + +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode(int x) : val(x), next(NULL) {} + * }; + */ +class Solution { +public: + ListNode* removeElements(ListNode* head, int val) { + if(head == nullptr) return nullptr; + + ListNode *newHead, *p, *tmp; + newHead->next = head; + p = newHead; + + while(p->next != nullptr) + { + if(p->next->val == val) + { + tmp = p->next; + p->next = p->next->next; + tmp = nullptr; + } + else + p = p->next; + } + + return newHead->next; + } +}; \ No newline at end of file From 276737cfb6e47f85372c852b95b6dd1af7d66f8d Mon Sep 17 00:00:00 2001 From: Ranger Date: Wed, 14 Oct 2015 16:43:38 +0800 Subject: [PATCH 55/57] 36 --- Valid Sudoku.txt | 59 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 Valid Sudoku.txt diff --git a/Valid Sudoku.txt b/Valid Sudoku.txt new file mode 100644 index 0000000..dffaa95 --- /dev/null +++ b/Valid Sudoku.txt @@ -0,0 +1,59 @@ +Determine if a Sudoku is valid, according to: Sudoku Puzzles - The Rules. + +The Sudoku board could be partially filled, where empty cells are filled with the character '.' + +A partially filled sudoku which is valid. + +Note: +A valid Sudoku board (partially filled) is not necessarily solvable. Only the filled cells need to be validated. + + +class Solution { +public: + bool isValidSudoku(vector>& board) { + int row[9], col[9]; + + for(int i = 0; i < 9; i++) + { + memset(row, 0 , sizeof(int) * 9); + memset(col, 0 , sizeof(int) * 9); + for(int j = 0; j < 9; j++) + { + if(board[i][j] != '.') + { + if(row[board[i][j]-'1']) + return false; + else + row[board[i][j]-'1']++; + } + + if(board[j][i] != '.') + { + if(col[board[j][i]-'1']) + return false; + else + col[board[j][i]-'1']++; + } + } + } + + for(int i = 0; i < 9; i+=3) + for(int j = 0; j < 9; j+=3) + { + memset(row, 0, sizeof(int) * 9); + for(int m = 0; m < 3; m++) + for(int n = 0; n < 3; n++) + { + if(board[i+m][j+n] != '.') + { + if(row[board[i+m][j+n]-'1']) + return false; + else + row[board[i+m][j+n]-'1']++; + } + } + } + + return true; + } +}; \ No newline at end of file From cdbdb7a8efd250e431a757b77aaf4b9143c2ab1a Mon Sep 17 00:00:00 2001 From: Ranger Date: Wed, 14 Oct 2015 17:31:14 +0800 Subject: [PATCH 56/57] 20 --- Valid Parentheses.txt | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 Valid Parentheses.txt diff --git a/Valid Parentheses.txt b/Valid Parentheses.txt new file mode 100644 index 0000000..9899685 --- /dev/null +++ b/Valid Parentheses.txt @@ -0,0 +1,37 @@ +Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. + +The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not. + + +class Solution { +public: + bool isValid(string s) { + stack ss; + if(s.size() % 2 != 0) return false; + for(int i = 0; i < s.size(); i++) + { + if(s[i] ==')') + { + if(!ss.empty() && ss.top() == '(') ss.pop(); + else return false; + } + else + if(!ss.empty() && s[i] ==']') + { + if(ss.top() == '[') ss.pop(); + else return false; + } + else + if(!ss.empty() && s[i] =='}') + { + if(ss.top() == '{') ss.pop(); + else return false; + } + else + ss.push(s[i]); + } + + if(ss.empty()) return true; + else return false; + } +}; \ No newline at end of file From 17628d6dba328aaffc455a7a92a378301f60a7da Mon Sep 17 00:00:00 2001 From: Ranger Date: Sun, 25 Oct 2015 22:42:51 +0800 Subject: [PATCH 57/57] 14 --- Longest Common Prefix.txt | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 Longest Common Prefix.txt diff --git a/Longest Common Prefix.txt b/Longest Common Prefix.txt new file mode 100644 index 0000000..dd7b8ea --- /dev/null +++ b/Longest Common Prefix.txt @@ -0,0 +1,32 @@ +Write a function to find the longest common prefix string amongst an array of strings. + + +class Solution { +public: + string longestCommonPrefix(vector& strs) { + int len = strs.size(); + if(len == 0) return ""; + if(len == 0) return strs[0]; + + string pre = ""; + char tmp; + + int min = strs[0].size(); + for(int i = 1; i < len; i++) + if(strs[i].size() < min) + min = strs[i].size(); + + for(int i = 0; i < min; i++) + { + tmp = strs[0][i]; + for(int j = 0; j < len; j++) + { + if(strs[j][i] != tmp) + return pre; + } + pre = pre + tmp; + } + + return pre; + } +}; \ No newline at end of file