From 8a33730ed144b8b1cdf4d42a6d4146c06223d8eb Mon Sep 17 00:00:00 2001 From: zczou Date: Sun, 16 Oct 2016 01:03:20 +0800 Subject: [PATCH 01/73] bitwise_AND_of_numbers_range --- README.md | 1 + .../bitwise_AND_of_numbers_range.go | 11 +++++++++++ 2 files changed, 12 insertions(+) create mode 100644 bitwise_AND_of_numbers_range/bitwise_AND_of_numbers_range.go diff --git a/README.md b/README.md index f789092..3c6ba61 100644 --- a/README.md +++ b/README.md @@ -159,6 +159,7 @@ Golang solution for leetcode. For each problem, there is a simple *_test.go to t #### [198. House Robber](https://github.com/hitzzc/go-leetcode/tree/master/house_robber) #### [199. Binary Tree Right Side View](https://github.com/hitzzc/go-leetcode/tree/master/binary_tree_right_side_view) #### [200. Number of Islands](https://github.com/hitzzc/go-leetcode/tree/master/number_of_islands) +#### [201. Bitwise AND of Numbers Range](https://github.com/hitzzc/go-leetcode/tree/master/bitwise_AND_of_numbers_range) diff --git a/bitwise_AND_of_numbers_range/bitwise_AND_of_numbers_range.go b/bitwise_AND_of_numbers_range/bitwise_AND_of_numbers_range.go new file mode 100644 index 0000000..8b98663 --- /dev/null +++ b/bitwise_AND_of_numbers_range/bitwise_AND_of_numbers_range.go @@ -0,0 +1,11 @@ +package bitwise_AND_of_numbers_range + +func rangeBitwiseAnd(m int, n int) int { + var cnt uint = 0 + for m != n { + cnt++ + m >>= 1 + n >>= 1 + } + return m << cnt +} From 11700e33fe3286ac0bf8c7cefddb23952c4c967d Mon Sep 17 00:00:00 2001 From: zczou Date: Sun, 16 Oct 2016 01:11:04 +0800 Subject: [PATCH 02/73] happy_number --- README.md | 1 + happy_number/happy_number.go | 22 ++++++++++++++++++++++ 2 files changed, 23 insertions(+) create mode 100644 happy_number/happy_number.go diff --git a/README.md b/README.md index 3c6ba61..6173111 100644 --- a/README.md +++ b/README.md @@ -160,6 +160,7 @@ Golang solution for leetcode. For each problem, there is a simple *_test.go to t #### [199. Binary Tree Right Side View](https://github.com/hitzzc/go-leetcode/tree/master/binary_tree_right_side_view) #### [200. Number of Islands](https://github.com/hitzzc/go-leetcode/tree/master/number_of_islands) #### [201. Bitwise AND of Numbers Range](https://github.com/hitzzc/go-leetcode/tree/master/bitwise_AND_of_numbers_range) +#### [202. Happy Number](https://github.com/hitzzc/go-leetcode/tree/master/happy_number) diff --git a/happy_number/happy_number.go b/happy_number/happy_number.go new file mode 100644 index 0000000..f724873 --- /dev/null +++ b/happy_number/happy_number.go @@ -0,0 +1,22 @@ +package happy_number + +func isHappy(n int) bool { + happened := map[int]bool{} + for n != 1 { + n = squares(n) + if happened[n] { + return false + } + happened[n] = true + } + return true +} + +func squares(n int) (ret int) { + for n > 0 { + num := n % 10 + ret += num * num + n /= 10 + } + return +} From ef62be0b0bc94a463de16cf026cc5806da1330e7 Mon Sep 17 00:00:00 2001 From: zczou Date: Sun, 16 Oct 2016 01:17:43 +0800 Subject: [PATCH 03/73] remove_linked_list_elements --- README.md | 1 + .../remove_linked_list_elements.go | 19 +++++++++++++++++++ 2 files changed, 20 insertions(+) create mode 100644 remove_linked_list_elements/remove_linked_list_elements.go diff --git a/README.md b/README.md index 6173111..785c5b5 100644 --- a/README.md +++ b/README.md @@ -161,6 +161,7 @@ Golang solution for leetcode. For each problem, there is a simple *_test.go to t #### [200. Number of Islands](https://github.com/hitzzc/go-leetcode/tree/master/number_of_islands) #### [201. Bitwise AND of Numbers Range](https://github.com/hitzzc/go-leetcode/tree/master/bitwise_AND_of_numbers_range) #### [202. Happy Number](https://github.com/hitzzc/go-leetcode/tree/master/happy_number) +#### [203. Remove Linked List Elements](https://github.com/hitzzc/go-leetcode/tree/master/remove_linked_list_elements) diff --git a/remove_linked_list_elements/remove_linked_list_elements.go b/remove_linked_list_elements/remove_linked_list_elements.go new file mode 100644 index 0000000..6011e24 --- /dev/null +++ b/remove_linked_list_elements/remove_linked_list_elements.go @@ -0,0 +1,19 @@ +package remove_linked_list_elements + +type ListNode struct { + Val int + Next *ListNode +} + +func removeElements(head *ListNode, val int) *ListNode { + fake := &ListNode{Next: head} + p := fake + for p != nil && p.Next != nil { + if p.Next.Val == val { + p.Next = p.Next.Next + } else { + p = p.Next + } + } + return fake.Next +} From 4c1ca8d30c393db495144840381c8b085c7398a5 Mon Sep 17 00:00:00 2001 From: zczou Date: Sun, 16 Oct 2016 10:20:09 +0800 Subject: [PATCH 04/73] 3 problems --- README.md | 3 +++ count_primes/count_primes.go | 22 ++++++++++++++++++++ isomorphic_strings/isomorphic_strings.go | 24 ++++++++++++++++++++++ reverse_linked_list/reverse_linked_list.go | 20 ++++++++++++++++++ 4 files changed, 69 insertions(+) create mode 100644 count_primes/count_primes.go create mode 100644 isomorphic_strings/isomorphic_strings.go create mode 100644 reverse_linked_list/reverse_linked_list.go diff --git a/README.md b/README.md index 785c5b5..c551563 100644 --- a/README.md +++ b/README.md @@ -162,6 +162,9 @@ Golang solution for leetcode. For each problem, there is a simple *_test.go to t #### [201. Bitwise AND of Numbers Range](https://github.com/hitzzc/go-leetcode/tree/master/bitwise_AND_of_numbers_range) #### [202. Happy Number](https://github.com/hitzzc/go-leetcode/tree/master/happy_number) #### [203. Remove Linked List Elements](https://github.com/hitzzc/go-leetcode/tree/master/remove_linked_list_elements) +#### [204. Count Primes](https://github.com/hitzzc/go-leetcode/tree/master/count_primes) +#### [205. Isomorphic Strings](https://github.com/hitzzc/go-leetcode/tree/master/isomorphic_strings) +#### [206. Reverse Linked List](https://github.com/hitzzc/go-leetcode/tree/master/reverse_linked_list) diff --git a/count_primes/count_primes.go b/count_primes/count_primes.go new file mode 100644 index 0000000..9c30d70 --- /dev/null +++ b/count_primes/count_primes.go @@ -0,0 +1,22 @@ +package count_primes + +func countPrimes(n int) int { + check := make([]bool, n) + for i := 2; i*i < n; i++ { + if check[i] { + continue + } + for j := i; i*j < n; j++ { + if !check[i*j] { + check[i*j] = true + } + } + } + cnt := 0 + for i := 2; i < n; i++ { + if !check[i] { + cnt++ + } + } + return cnt +} diff --git a/isomorphic_strings/isomorphic_strings.go b/isomorphic_strings/isomorphic_strings.go new file mode 100644 index 0000000..42e70d4 --- /dev/null +++ b/isomorphic_strings/isomorphic_strings.go @@ -0,0 +1,24 @@ +package isomorphic_strings + +func isIsomorphic(s string, t string) bool { + if len(s) != len(t) { + return false + } + m := map[byte]byte{} + n := map[byte]byte{} + for i := range s { + if _, ok := m[t[i]]; !ok { + m[t[i]] = s[i] + } + if _, ok := n[s[i]]; !ok { + n[s[i]] = t[i] + } + if s[i] != m[t[i]] { + return false + } + if t[i] != n[s[i]] { + return false + } + } + return true +} diff --git a/reverse_linked_list/reverse_linked_list.go b/reverse_linked_list/reverse_linked_list.go new file mode 100644 index 0000000..0635c9a --- /dev/null +++ b/reverse_linked_list/reverse_linked_list.go @@ -0,0 +1,20 @@ +package reverse_linked_list + +type ListNode struct { + Val int + Next *ListNode +} + +func reverseList(head *ListNode) *ListNode { + var tail, next *ListNode + for head != nil && head.Next != nil { + next = head.Next + head.Next = tail + tail = head + head = next + } + if head != nil { + head.Next = tail + } + return head +} From f6bf5d47720cf8c62becf526ef385f649ceab18b Mon Sep 17 00:00:00 2001 From: zczou Date: Sun, 16 Oct 2016 11:34:06 +0800 Subject: [PATCH 05/73] 2 problems --- README.md | 2 + course_schedule/course_schedule.go | 70 ++++++++++++++++++++++++++++++ implement_trie/implement_trie.cpp | 56 ++++++++++++++++++++++++ 3 files changed, 128 insertions(+) create mode 100644 course_schedule/course_schedule.go create mode 100644 implement_trie/implement_trie.cpp diff --git a/README.md b/README.md index c551563..17b0fe9 100644 --- a/README.md +++ b/README.md @@ -165,6 +165,8 @@ Golang solution for leetcode. For each problem, there is a simple *_test.go to t #### [204. Count Primes](https://github.com/hitzzc/go-leetcode/tree/master/count_primes) #### [205. Isomorphic Strings](https://github.com/hitzzc/go-leetcode/tree/master/isomorphic_strings) #### [206. Reverse Linked List](https://github.com/hitzzc/go-leetcode/tree/master/reverse_linked_list) +#### [207. Course Schedule](https://github.com/hitzzc/go-leetcode/tree/master/course_schedule) +#### [208. Implement Trie (Prefix Tree)](https://github.com/hitzzc/go-leetcode/tree/master/implement_trie) diff --git a/course_schedule/course_schedule.go b/course_schedule/course_schedule.go new file mode 100644 index 0000000..246bb4b --- /dev/null +++ b/course_schedule/course_schedule.go @@ -0,0 +1,70 @@ +package course_schedule + +// BFS +func canFinish(numCourses int, prerequisites [][]int) bool { + graph := map[int][]int{} + inDegree := make([]int, numCourses) + for i := range prerequisites { + graph[prerequisites[i][1]] = append(graph[prerequisites[i][1]], prerequisites[i][0]) + inDegree[prerequisites[i][0]]++ + } + queue := []int{} + for i := range inDegree { + if inDegree[i] == 0 { + queue = append(queue, i) + } + } + for len(queue) != 0 { + head := queue[0] + queue = queue[1:] + for i := range graph[head] { + inDegree[graph[head][i]]-- + if inDegree[graph[head][i]] == 0 { + queue = append(queue, graph[head][i]) + } + } + } + for i := range inDegree { + if inDegree[i] != 0 { + return false + } + } + return true +} + +// DFS +func canFinishDFS(numCourses int, prerequisites [][]int) bool { + graph := map[int][]int{} + for i := range prerequisites { + graph[prerequisites[i][1]] = append(graph[prerequisites[i][1]], prerequisites[i][0]) + } + path := make([]bool, numCourses) + visited := make([]bool, numCourses) + for i := 0; i < numCourses; i++ { + if visited[i] { + continue + } + if hasCycle(i, graph, path, visited) { + return false + } + } + return true +} + +func hasCycle(start int, graph map[int][]int, path []bool, visited []bool) bool { + for i := range graph[start] { + if visited[graph[start][i]] { + continue + } + if path[graph[start][i]] { + return true + } + path[graph[start][i]] = true + if hasCycle(graph[start][i], graph, path, visited) { + return true + } + path[graph[start][i]] = false + } + visited[start] = true + return false +} diff --git a/implement_trie/implement_trie.cpp b/implement_trie/implement_trie.cpp new file mode 100644 index 0000000..0ef9c5c --- /dev/null +++ b/implement_trie/implement_trie.cpp @@ -0,0 +1,56 @@ +#include +using namespace std; + +class TrieNode { +public: + TrieNode(): is_word_(false) {} +public: + bool is_word_; + unordered_map children; +}; + +class Trie { +public: + Trie() { + root = new TrieNode(); + } + + // Inserts a word into the trie. + void insert(string word) { + if (word.size() <= 0) return; + TrieNode* node = root; + for (int i = 0; i < word.size(); ++i){ + if (node->children.find(word[i]) == node->children.end()){ + node->children[word[i]] = new TrieNode(); + } + node = node->children[word[i]]; + } + node->is_word_ = true; + return; + } + + // Returns if the word is in the trie. + bool search(string word) { + return retrieve(word, false); + } + + // Returns if there is any word in the trie + // that starts with the given prefix. + bool startsWith(string prefix) { + return retrieve(prefix, true); + } + +private: + TrieNode* root; +private: + bool retrieve(string& key, bool prefix){ + if (key.size() <= 0) return false; + TrieNode* node = root; + for (int i = 0; i < key.size(); i++){ + if (node->children.find(key[i]) == node->children.end()) + return false; + node = node->children[key[i]]; + } + return prefix ? true : node->is_word_; + } +}; \ No newline at end of file From 28fe57e95dcde8b2f9d3e07df3fbdf44475e99d4 Mon Sep 17 00:00:00 2001 From: zczou Date: Sun, 16 Oct 2016 13:51:33 +0800 Subject: [PATCH 06/73] solve 4 problems --- README.md | 4 ++ add_and_search_word/add_and_search_word.cpp | 52 +++++++++++++++++++ course_schedule_II/course_schedule_II.go | 32 ++++++++++++ house_robber_II/house_robber_II.go | 33 ++++++++++++ .../minimum_size_subarray_sum.go | 21 ++++++++ 5 files changed, 142 insertions(+) create mode 100644 add_and_search_word/add_and_search_word.cpp create mode 100644 course_schedule_II/course_schedule_II.go create mode 100644 house_robber_II/house_robber_II.go create mode 100644 minimum_size_subarray_sum/minimum_size_subarray_sum.go diff --git a/README.md b/README.md index 17b0fe9..2e5c878 100644 --- a/README.md +++ b/README.md @@ -167,6 +167,10 @@ Golang solution for leetcode. For each problem, there is a simple *_test.go to t #### [206. Reverse Linked List](https://github.com/hitzzc/go-leetcode/tree/master/reverse_linked_list) #### [207. Course Schedule](https://github.com/hitzzc/go-leetcode/tree/master/course_schedule) #### [208. Implement Trie (Prefix Tree)](https://github.com/hitzzc/go-leetcode/tree/master/implement_trie) +#### [209. Minimum Size Subarray Sum](https://github.com/hitzzc/go-leetcode/tree/master/minimum_size_subarray_sum) +#### [210. Course Schedule II](https://github.com/hitzzc/go-leetcode/tree/master/course_schedule_II) +#### [211. Add and Search Word - Data structure design](https://github.com/hitzzc/go-leetcode/tree/master/add_and_search_word) +#### [213. House Robber II](https://github.com/hitzzc/go-leetcode/tree/master/add_and_search_word) diff --git a/add_and_search_word/add_and_search_word.cpp b/add_and_search_word/add_and_search_word.cpp new file mode 100644 index 0000000..dfdab38 --- /dev/null +++ b/add_and_search_word/add_and_search_word.cpp @@ -0,0 +1,52 @@ +#include +using namespace std; + +struct TrieNode { + bool is_word_; + unordered_map children; + TrieNode(): is_word_(false) {} +}; + +class WordDictionary { +public: + TrieNode* root; + WordDictionary() { + root = new TrieNode(); + } + // Adds a word into the data structure. + void addWord(string word) { + if (word.size() <= 0) return; + TrieNode* node = root; + for (int i = 0; i < word.size(); ++i){ + if (node->children.find(word[i]) == node->children.end()){ + node->children[word[i]] = new TrieNode(); + } + node = node->children[word[i]]; + } + node->is_word_ = true; + } + + // Returns if the word is in the data structure. A word could + // contain the dot character '.' to represent any one letter. + bool search(string word) { + return retrieve(word, root, 0, word.size()); + } + + bool retrieve(string& word, TrieNode* node, int idx, int length) { + if (idx == length) return node->is_word_; + if (word[idx] == '.') { + if (node->children.size() == 0) { + return false; + } + for (auto& kv: node->children) { + if (retrieve(word, kv.second, idx+1, length)) { + return true; + } + } + return false; + }else if (node->children.find(word[idx]) != node->children.end()) { + return retrieve(word, node->children[word[idx]], idx+1, length); + } + return false; + } +}; diff --git a/course_schedule_II/course_schedule_II.go b/course_schedule_II/course_schedule_II.go new file mode 100644 index 0000000..712967c --- /dev/null +++ b/course_schedule_II/course_schedule_II.go @@ -0,0 +1,32 @@ +package course_schedule_II + +func findOrder(numCourses int, prerequisites [][]int) []int { + graph := map[int][]int{} + inDegree := make([]int, numCourses) + for i := range prerequisites { + graph[prerequisites[i][1]] = append(graph[prerequisites[i][1]], prerequisites[i][0]) + inDegree[prerequisites[i][0]]++ + } + queue := []int{} + for i := range inDegree { + if inDegree[i] == 0 { + queue = append(queue, i) + } + } + ret := []int{} + for len(queue) != 0 { + head := queue[0] + queue = queue[1:] + for i := range graph[head] { + inDegree[graph[head][i]]-- + if inDegree[graph[head][i]] == 0 { + queue = append(queue, graph[head][i]) + } + } + ret = append(ret, head) + } + if len(ret) != numCourses { + return []int{} + } + return ret +} diff --git a/house_robber_II/house_robber_II.go b/house_robber_II/house_robber_II.go new file mode 100644 index 0000000..943dc1a --- /dev/null +++ b/house_robber_II/house_robber_II.go @@ -0,0 +1,33 @@ +package house_robber_II + +func rob(nums []int) int { + if len(nums) == 0 { + return 0 + } + if len(nums) == 1 { + return nums[0] + } + if len(nums) == 2 { + return max(nums[0], nums[1]) + } + x := helper(nums, 0, len(nums)-2) + y := helper(nums, 1, len(nums)-1) + return max(x, y) +} + +func helper(nums []int, i, j int) int { + var n1, n2, current int + for ; i <= j; i++ { + current = max(n1, n2+nums[i]) + n2 = n1 + n1 = current + } + return n1 +} + +func max(i, j int) int { + if i > j { + return i + } + return j +} diff --git a/minimum_size_subarray_sum/minimum_size_subarray_sum.go b/minimum_size_subarray_sum/minimum_size_subarray_sum.go new file mode 100644 index 0000000..df18af0 --- /dev/null +++ b/minimum_size_subarray_sum/minimum_size_subarray_sum.go @@ -0,0 +1,21 @@ +package minimum_size_subarray_sum + +func minSubArrayLen(s int, nums []int) int { + var left, right, res int + min := len(nums) + 1 + for right < len(nums) { + for ; res < s && right < len(nums); right++ { + res += nums[right] + } + for ; res >= s; left++ { + res -= nums[left] + if right-left < min { + min = right - left + } + } + } + if min == len(nums)+1 { + return 0 + } + return min +} From 8694d0ae709f85741949403acc393f9cece83514 Mon Sep 17 00:00:00 2001 From: zczou Date: Sun, 16 Oct 2016 23:39:44 +0800 Subject: [PATCH 07/73] shortest_palindrome --- README.md | 1 + shortest_palindrome/shortest_palindrome.go | 31 ++++++++++++++++++++++ 2 files changed, 32 insertions(+) create mode 100644 shortest_palindrome/shortest_palindrome.go diff --git a/README.md b/README.md index 2e5c878..f1e720e 100644 --- a/README.md +++ b/README.md @@ -171,6 +171,7 @@ Golang solution for leetcode. For each problem, there is a simple *_test.go to t #### [210. Course Schedule II](https://github.com/hitzzc/go-leetcode/tree/master/course_schedule_II) #### [211. Add and Search Word - Data structure design](https://github.com/hitzzc/go-leetcode/tree/master/add_and_search_word) #### [213. House Robber II](https://github.com/hitzzc/go-leetcode/tree/master/add_and_search_word) +#### [214. Shortest Palindrome (unsolved)](https://github.com/hitzzc/go-leetcode/tree/master/shortest_palindrome) diff --git a/shortest_palindrome/shortest_palindrome.go b/shortest_palindrome/shortest_palindrome.go new file mode 100644 index 0000000..381b1d4 --- /dev/null +++ b/shortest_palindrome/shortest_palindrome.go @@ -0,0 +1,31 @@ +package shortest_palindrome + +func shortestPalindrome(s string) string { + matrix := make([][]bool, len(s)) + for i := range matrix { + matrix[i] = make([]bool, len(s)) + } + for i := len(matrix) - 1; i >= 0; i-- { + for j := i; j < len(matrix[i]); j++ { + if j == i || s[i] == s[j] && (i+1 == j || matrix[i+1][j-1]) { + matrix[i][j] = true + } + } + } + + p := len(s) - 1 + for ; p >= 0; p-- { + if matrix[0][p] { + break + } + } + return reverse(s[p+1:]) + s +} + +func reverse(s string) string { + bytes := make([]byte, len(s)) + for i := range s { + bytes[len(s)-i-1] = s[i] + } + return string(bytes) +} From 9fab52c88c18d06c427121670a152213e27411d6 Mon Sep 17 00:00:00 2001 From: zczou Date: Sun, 16 Oct 2016 23:52:40 +0800 Subject: [PATCH 08/73] kth_largest_element_in_an_array --- README.md | 1 + .../kth_largest_element_in_an_array.go | 23 +++++++++++++++++++ 2 files changed, 24 insertions(+) create mode 100644 kth_largest_element_in_an_array/kth_largest_element_in_an_array.go diff --git a/README.md b/README.md index f1e720e..28fb172 100644 --- a/README.md +++ b/README.md @@ -172,6 +172,7 @@ Golang solution for leetcode. For each problem, there is a simple *_test.go to t #### [211. Add and Search Word - Data structure design](https://github.com/hitzzc/go-leetcode/tree/master/add_and_search_word) #### [213. House Robber II](https://github.com/hitzzc/go-leetcode/tree/master/add_and_search_word) #### [214. Shortest Palindrome (unsolved)](https://github.com/hitzzc/go-leetcode/tree/master/shortest_palindrome) +#### [215. Kth Largest Element in an Array](https://github.com/hitzzc/go-leetcode/tree/master/kth_largest_element_in_an_array) diff --git a/kth_largest_element_in_an_array/kth_largest_element_in_an_array.go b/kth_largest_element_in_an_array/kth_largest_element_in_an_array.go new file mode 100644 index 0000000..ceec76c --- /dev/null +++ b/kth_largest_element_in_an_array/kth_largest_element_in_an_array.go @@ -0,0 +1,23 @@ +package kth_largest_element_in_an_array + +func findKthLargest(nums []int, k int) int { + return partition(nums, 0, len(nums)-1, k) +} + +func partition(nums []int, i, j, k int) (ret int) { + p := i + for m := i; m < j; m++ { + if nums[m] > nums[j] { + nums[p], nums[m] = nums[m], nums[p] + p++ + } + } + nums[p], nums[j] = nums[j], nums[p] + if p+1 == k { + return nums[p] + } + if k < p+1 { + return partition(nums, i, p-1, k) + } + return partition(nums, p+1, j, k) +} From 310e9431c86b4d8003d3210b3965c144fb4542e6 Mon Sep 17 00:00:00 2001 From: zczou Date: Mon, 17 Oct 2016 00:04:38 +0800 Subject: [PATCH 09/73] combinations_sum_III --- README.md | 1 + combinations_sum_III/combinations_sum_III.go | 21 ++++++++++++++++++++ 2 files changed, 22 insertions(+) create mode 100644 combinations_sum_III/combinations_sum_III.go diff --git a/README.md b/README.md index 28fb172..6bc017a 100644 --- a/README.md +++ b/README.md @@ -173,6 +173,7 @@ Golang solution for leetcode. For each problem, there is a simple *_test.go to t #### [213. House Robber II](https://github.com/hitzzc/go-leetcode/tree/master/add_and_search_word) #### [214. Shortest Palindrome (unsolved)](https://github.com/hitzzc/go-leetcode/tree/master/shortest_palindrome) #### [215. Kth Largest Element in an Array](https://github.com/hitzzc/go-leetcode/tree/master/kth_largest_element_in_an_array) +#### [216. Combination Sum III](https://github.com/hitzzc/go-leetcode/tree/master/combinations_sum_III) diff --git a/combinations_sum_III/combinations_sum_III.go b/combinations_sum_III/combinations_sum_III.go new file mode 100644 index 0000000..9219fd7 --- /dev/null +++ b/combinations_sum_III/combinations_sum_III.go @@ -0,0 +1,21 @@ +package combinations_sum_III + +func combinationSum3(k int, n int) [][]int { + return DFS(0, 1, k, n, []int{}) +} + +func DFS(level int, start int, k int, n int, path []int) (ret [][]int) { + if level == k && n == 0 { + cp := make([]int, len(path)) + copy(cp, path) + ret = append(ret, cp) + return + } + for i := start; i <= n && i <= 9; i++ { + path = append(path, i) + tmpRet := DFS(level+1, i+1, k, n-i, path) + ret = append(ret, tmpRet...) + path = path[:len(path)-1] + } + return +} From 983afbfd871718c33e1ccb3aefcccdda8a89b854 Mon Sep 17 00:00:00 2001 From: zczou Date: Mon, 17 Oct 2016 16:17:33 +0800 Subject: [PATCH 10/73] 3 --- README.md | 3 +++ contains_duplicate/contains_duplicate.go | 12 ++++++++++++ contains_duplicate_II/contains_duplicate_II.go | 14 ++++++++++++++ contains_duplicate_III/contains_duplicate_III.go | 5 +++++ 4 files changed, 34 insertions(+) create mode 100644 contains_duplicate/contains_duplicate.go create mode 100644 contains_duplicate_II/contains_duplicate_II.go create mode 100644 contains_duplicate_III/contains_duplicate_III.go diff --git a/README.md b/README.md index 6bc017a..bc0db95 100644 --- a/README.md +++ b/README.md @@ -174,6 +174,9 @@ Golang solution for leetcode. For each problem, there is a simple *_test.go to t #### [214. Shortest Palindrome (unsolved)](https://github.com/hitzzc/go-leetcode/tree/master/shortest_palindrome) #### [215. Kth Largest Element in an Array](https://github.com/hitzzc/go-leetcode/tree/master/kth_largest_element_in_an_array) #### [216. Combination Sum III](https://github.com/hitzzc/go-leetcode/tree/master/combinations_sum_III) +#### [217. Contains Duplicate](https://github.com/hitzzc/go-leetcode/tree/master/contains_duplicate) +#### [218. Contains Duplicate II](https://github.com/hitzzc/go-leetcode/tree/master/contains_duplicate_II) +#### [219. Contains Duplicate III (unsolved)](https://github.com/hitzzc/go-leetcode/tree/master/contains_duplicate_III) diff --git a/contains_duplicate/contains_duplicate.go b/contains_duplicate/contains_duplicate.go new file mode 100644 index 0000000..a363e8d --- /dev/null +++ b/contains_duplicate/contains_duplicate.go @@ -0,0 +1,12 @@ +package contains_duplicate + +func containsDuplicate(nums []int) bool { + m := map[int]bool{} + for i := range nums { + if m[nums[i]] { + return true + } + m[nums[i]] = true + } + return false +} diff --git a/contains_duplicate_II/contains_duplicate_II.go b/contains_duplicate_II/contains_duplicate_II.go new file mode 100644 index 0000000..7548cf6 --- /dev/null +++ b/contains_duplicate_II/contains_duplicate_II.go @@ -0,0 +1,14 @@ +package contains_duplicate_II + +func containsNearbyDuplicate(nums []int, k int) bool { + m := map[int]int{} + for i := range nums { + if j, ok := m[nums[i]]; ok { + if i-j <= k { + return true + } + } + m[nums[i]] = i + } + return false +} diff --git a/contains_duplicate_III/contains_duplicate_III.go b/contains_duplicate_III/contains_duplicate_III.go new file mode 100644 index 0000000..66df47e --- /dev/null +++ b/contains_duplicate_III/contains_duplicate_III.go @@ -0,0 +1,5 @@ +package contains_duplicate_III + +func containsNearbyAlmostDuplicate(nums []int, k int, t int) bool { + +} From cc1d44e1a562207e26b1637bb90ea3a508ef0884 Mon Sep 17 00:00:00 2001 From: zczou Date: Mon, 17 Oct 2016 16:41:22 +0800 Subject: [PATCH 11/73] maximal_square --- README.md | 1 + maximal_square/maximal_square.go | 36 ++++++++++++++++++++++++++++++++ 2 files changed, 37 insertions(+) create mode 100644 maximal_square/maximal_square.go diff --git a/README.md b/README.md index bc0db95..38e4148 100644 --- a/README.md +++ b/README.md @@ -177,6 +177,7 @@ Golang solution for leetcode. For each problem, there is a simple *_test.go to t #### [217. Contains Duplicate](https://github.com/hitzzc/go-leetcode/tree/master/contains_duplicate) #### [218. Contains Duplicate II](https://github.com/hitzzc/go-leetcode/tree/master/contains_duplicate_II) #### [219. Contains Duplicate III (unsolved)](https://github.com/hitzzc/go-leetcode/tree/master/contains_duplicate_III) +#### [221. Maximal Square](https://github.com/hitzzc/go-leetcode/tree/master/maximal_square) diff --git a/maximal_square/maximal_square.go b/maximal_square/maximal_square.go new file mode 100644 index 0000000..667e3f5 --- /dev/null +++ b/maximal_square/maximal_square.go @@ -0,0 +1,36 @@ +package maximal_square + +func maximalSquare(matrix [][]byte) int { + if len(matrix) == 0 || len(matrix[0]) == 0 { + return 0 + } + m := map[byte]int{ + '0': 0, + '1': 1, + } + p := make([][]int, len(matrix)) + for i := range p { + p[i] = make([]int, len(matrix[i])) + } + max := 0 + for i := range matrix { + for j := range matrix[i] { + if i == 0 || j == 0 { + p[i][j] = m[matrix[i][j]] + } else if matrix[i][j] == '1' { + p[i][j] = min(min(p[i-1][j], p[i][j-1]), p[i-1][j-1]) + 1 + } + if p[i][j] > max { + max = p[i][j] + } + } + } + return max * max +} + +func min(i, j int) int { + if i < j { + return i + } + return j +} From 7d207fa861ec3959b84189f7f7523ea17e06ecf8 Mon Sep 17 00:00:00 2001 From: zczou Date: Mon, 17 Oct 2016 17:02:01 +0800 Subject: [PATCH 12/73] count_complete_tree_nodes --- README.md | 5 ++-- .../count_complete_tree_nodes.cpp | 25 +++++++++++++++++++ 2 files changed, 28 insertions(+), 2 deletions(-) create mode 100644 count_complete_tree_nodes/count_complete_tree_nodes.cpp diff --git a/README.md b/README.md index 38e4148..1c6f3e0 100644 --- a/README.md +++ b/README.md @@ -175,9 +175,10 @@ Golang solution for leetcode. For each problem, there is a simple *_test.go to t #### [215. Kth Largest Element in an Array](https://github.com/hitzzc/go-leetcode/tree/master/kth_largest_element_in_an_array) #### [216. Combination Sum III](https://github.com/hitzzc/go-leetcode/tree/master/combinations_sum_III) #### [217. Contains Duplicate](https://github.com/hitzzc/go-leetcode/tree/master/contains_duplicate) -#### [218. Contains Duplicate II](https://github.com/hitzzc/go-leetcode/tree/master/contains_duplicate_II) -#### [219. Contains Duplicate III (unsolved)](https://github.com/hitzzc/go-leetcode/tree/master/contains_duplicate_III) +#### [219. Contains Duplicate II](https://github.com/hitzzc/go-leetcode/tree/master/contains_duplicate_II) +#### [220. Contains Duplicate III (unsolved)](https://github.com/hitzzc/go-leetcode/tree/master/contains_duplicate_III) #### [221. Maximal Square](https://github.com/hitzzc/go-leetcode/tree/master/maximal_square) +#### [222. Count Complete Tree Nodes](https://github.com/hitzzc/go-leetcode/tree/master/count_complete_tree_nodes) diff --git a/count_complete_tree_nodes/count_complete_tree_nodes.cpp b/count_complete_tree_nodes/count_complete_tree_nodes.cpp new file mode 100644 index 0000000..5358fdf --- /dev/null +++ b/count_complete_tree_nodes/count_complete_tree_nodes.cpp @@ -0,0 +1,25 @@ +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode(int x) : val(x), left(NULL), right(NULL) {} +}; + +class Solution { +public: + int countNodes(TreeNode* root) { + int depth = 0; + TreeNode *left, *right; + left = right = root; + while (left!=NULL && right!=NULL){ + left = left->left; + right = right->right; + ++depth; + } + if (left==NULL && right==NULL) + return (1<left); + int cnt2 = countNodes(root->right); + return cnt1 + cnt2 + 1; + } +}; \ No newline at end of file From 246b884d85d3d8398dfa47580851ed31ee1d5271 Mon Sep 17 00:00:00 2001 From: zczou Date: Mon, 17 Oct 2016 17:25:57 +0800 Subject: [PATCH 13/73] rectangle_area --- README.md | 1 + rectangle_area/rectangle_area.go | 26 ++++++++++++++++++++++++++ 2 files changed, 27 insertions(+) create mode 100644 rectangle_area/rectangle_area.go diff --git a/README.md b/README.md index 1c6f3e0..7213e82 100644 --- a/README.md +++ b/README.md @@ -179,6 +179,7 @@ Golang solution for leetcode. For each problem, there is a simple *_test.go to t #### [220. Contains Duplicate III (unsolved)](https://github.com/hitzzc/go-leetcode/tree/master/contains_duplicate_III) #### [221. Maximal Square](https://github.com/hitzzc/go-leetcode/tree/master/maximal_square) #### [222. Count Complete Tree Nodes](https://github.com/hitzzc/go-leetcode/tree/master/count_complete_tree_nodes) +#### [223. Rectangle Area](https://github.com/hitzzc/go-leetcode/tree/master/rectangle_area) diff --git a/rectangle_area/rectangle_area.go b/rectangle_area/rectangle_area.go new file mode 100644 index 0000000..cea21c1 --- /dev/null +++ b/rectangle_area/rectangle_area.go @@ -0,0 +1,26 @@ +package rectangle_area + +func computeArea(A int, B int, C int, D int, E int, F int, G int, H int) int { + if C <= E || G <= A || D <= F || H <= B { + return (C-A)*(D-B) + (G-E)*(H-F) + } + left := max(A, E) + bottom := max(B, F) + right := min(C, G) + top := min(D, H) + return (C-A)*(D-B) + (G-E)*(H-F) - (right-left)*(top-bottom) +} + +func min(i, j int) int { + if i < j { + return i + } + return j +} + +func max(i, j int) int { + if i > j { + return i + } + return j +} From 47f50e9c9897a4ec9b1c47f5f6fa143220a23809 Mon Sep 17 00:00:00 2001 From: zczou Date: Mon, 17 Oct 2016 17:55:00 +0800 Subject: [PATCH 14/73] basic_calculator/ --- README.md | 1 + basic_calculator/basic_calculator.go | 32 ++++++++++++++++++++++++++++ 2 files changed, 33 insertions(+) create mode 100644 basic_calculator/basic_calculator.go diff --git a/README.md b/README.md index 7213e82..8c581d9 100644 --- a/README.md +++ b/README.md @@ -180,6 +180,7 @@ Golang solution for leetcode. For each problem, there is a simple *_test.go to t #### [221. Maximal Square](https://github.com/hitzzc/go-leetcode/tree/master/maximal_square) #### [222. Count Complete Tree Nodes](https://github.com/hitzzc/go-leetcode/tree/master/count_complete_tree_nodes) #### [223. Rectangle Area](https://github.com/hitzzc/go-leetcode/tree/master/rectangle_area) +#### [224. Basic Calculator](https://github.com/hitzzc/go-leetcode/tree/master/basic_calculator) diff --git a/basic_calculator/basic_calculator.go b/basic_calculator/basic_calculator.go new file mode 100644 index 0000000..5455c96 --- /dev/null +++ b/basic_calculator/basic_calculator.go @@ -0,0 +1,32 @@ +package basic_calculator + +func calculate(s string) int { + ret := 0 + stack := []int{} + sign := 1 + for i := 0; i < len(s); i++ { + if s[i] >= '0' && s[i] <= '9' { + num := 0 + for ; i < len(s) && s[i] >= '0' && s[i] <= '9'; i++ { + num = 10*num + int(s[i]-'0') + } + ret += sign * num + i-- + } else if s[i] == '+' { + sign = 1 + } else if s[i] == '-' { + sign = -1 + } else if s[i] == '(' { + stack = append(stack, ret, sign) + ret = 0 + sign = 1 + } else if s[i] == ')' { + signTmp := stack[len(stack)-1] + retTmp := stack[len(stack)-2] + stack = stack[:len(stack)-2] + ret = signTmp*ret + retTmp + sign = 1 + } + } + return ret +} From 4945e38d3d9c40a85c70f89951af327dd9253188 Mon Sep 17 00:00:00 2001 From: zczou Date: Mon, 17 Oct 2016 18:08:34 +0800 Subject: [PATCH 15/73] implement_stack_using_queues --- README.md | 1 + .../implement_stack_using_queues.cpp | 30 +++++++++++++++++++ 2 files changed, 31 insertions(+) create mode 100644 implement_stack_using_queues/implement_stack_using_queues.cpp diff --git a/README.md b/README.md index 8c581d9..e58d7c5 100644 --- a/README.md +++ b/README.md @@ -181,6 +181,7 @@ Golang solution for leetcode. For each problem, there is a simple *_test.go to t #### [222. Count Complete Tree Nodes](https://github.com/hitzzc/go-leetcode/tree/master/count_complete_tree_nodes) #### [223. Rectangle Area](https://github.com/hitzzc/go-leetcode/tree/master/rectangle_area) #### [224. Basic Calculator](https://github.com/hitzzc/go-leetcode/tree/master/basic_calculator) +#### [225. Implement Stack using Queues](https://github.com/hitzzc/go-leetcode/tree/master/implement_stack_using_queues) diff --git a/implement_stack_using_queues/implement_stack_using_queues.cpp b/implement_stack_using_queues/implement_stack_using_queues.cpp new file mode 100644 index 0000000..f97b377 --- /dev/null +++ b/implement_stack_using_queues/implement_stack_using_queues.cpp @@ -0,0 +1,30 @@ +#include + +class Stack { +public: + queue q; + // Push element x onto stack. + void push(int x) { + q.push(x); + } + + // Removes the element on top of the stack. + void pop() { + int num = q.size() - 1; + while (num-- > 0){ + q.push(q.front()); + q.pop(); + } + q.pop(); + } + + // Get the top element. + int top() { + return q.back(); + } + + // Return whether the stack is empty. + bool empty() { + return q.empty(); + } +}; \ No newline at end of file From ffc0de7d068c59096ca950942593055871233ed2 Mon Sep 17 00:00:00 2001 From: zczou Date: Mon, 17 Oct 2016 18:15:35 +0800 Subject: [PATCH 16/73] invert_binary_tree --- README.md | 1 + invert_binary_tree/invert_binary_tree.go | 17 +++++++++++++++++ 2 files changed, 18 insertions(+) create mode 100644 invert_binary_tree/invert_binary_tree.go diff --git a/README.md b/README.md index e58d7c5..4e8a527 100644 --- a/README.md +++ b/README.md @@ -182,6 +182,7 @@ Golang solution for leetcode. For each problem, there is a simple *_test.go to t #### [223. Rectangle Area](https://github.com/hitzzc/go-leetcode/tree/master/rectangle_area) #### [224. Basic Calculator](https://github.com/hitzzc/go-leetcode/tree/master/basic_calculator) #### [225. Implement Stack using Queues](https://github.com/hitzzc/go-leetcode/tree/master/implement_stack_using_queues) +#### [226. Invert Binary Tree](https://github.com/hitzzc/go-leetcode/tree/master/invert_binary_tree) diff --git a/invert_binary_tree/invert_binary_tree.go b/invert_binary_tree/invert_binary_tree.go new file mode 100644 index 0000000..d139641 --- /dev/null +++ b/invert_binary_tree/invert_binary_tree.go @@ -0,0 +1,17 @@ +package invert_binary_tree + +type TreeNode struct { + Val int + Left *TreeNode + Right *TreeNode +} + +func invertTree(root *TreeNode) *TreeNode { + if root == nil { + return nil + } + root.Left, root.Right = root.Right, root.Left + invertTree(root.Right) + invertTree(root.Left) + return root +} From bde3c2b6ca941a1b88ee040f5e7a7095f113252c Mon Sep 17 00:00:00 2001 From: zczou Date: Mon, 17 Oct 2016 21:07:52 +0800 Subject: [PATCH 17/73] basic_calculator_II --- README.md | 2 +- basic_calculator_II/basic_calculator_II.go | 57 ++++++++++++++++++++++ 2 files changed, 58 insertions(+), 1 deletion(-) create mode 100644 basic_calculator_II/basic_calculator_II.go diff --git a/README.md b/README.md index 4e8a527..bbce49c 100644 --- a/README.md +++ b/README.md @@ -183,7 +183,7 @@ Golang solution for leetcode. For each problem, there is a simple *_test.go to t #### [224. Basic Calculator](https://github.com/hitzzc/go-leetcode/tree/master/basic_calculator) #### [225. Implement Stack using Queues](https://github.com/hitzzc/go-leetcode/tree/master/implement_stack_using_queues) #### [226. Invert Binary Tree](https://github.com/hitzzc/go-leetcode/tree/master/invert_binary_tree) - +#### [227. Basic Calculator II](https://github.com/hitzzc/go-leetcode/tree/master/basic_calculator_II) diff --git a/basic_calculator_II/basic_calculator_II.go b/basic_calculator_II/basic_calculator_II.go new file mode 100644 index 0000000..775469c --- /dev/null +++ b/basic_calculator_II/basic_calculator_II.go @@ -0,0 +1,57 @@ +package basic_calculator_II + +func calculate(s string) int { + numStack := []int{} + opStack := []byte{} + for i := 0; i < len(s); i++ { + if s[i] >= '0' && s[i] <= '9' { + num := 0 + for ; i < len(s) && s[i] >= '0' && s[i] <= '9'; i++ { + num = 10*num + int(s[i]-'0') + } + numStack = append(numStack, num) + i-- + } else if s[i] == ' ' { + continue + } else { + for len(opStack) != 0 && priority(opStack[len(opStack)-1]) >= priority(s[i]) { + num := operate(numStack[len(numStack)-2], numStack[len(numStack)-1], opStack[len(opStack)-1]) + numStack[len(numStack)-2] = num + numStack = numStack[:len(numStack)-1] + opStack = opStack[:len(opStack)-1] + } + opStack = append(opStack, s[i]) + } + } + for len(opStack) != 0 { + num := operate(numStack[len(numStack)-2], numStack[len(numStack)-1], opStack[len(opStack)-1]) + numStack[len(numStack)-2] = num + numStack = numStack[:len(numStack)-1] + opStack = opStack[:len(opStack)-1] + } + return numStack[0] +} + +func priority(op byte) int { + switch op { + case '*', '/': + return 2 + case '+', '-': + return 1 + } + return 0 +} + +func operate(i, j int, op byte) int { + switch op { + case '+': + return i + j + case '-': + return i - j + case '*': + return i * j + case '/': + return i / j + } + return 0 +} From 103e10792c969d93c8170230f657b87099830ed6 Mon Sep 17 00:00:00 2001 From: zczou Date: Mon, 17 Oct 2016 23:39:14 +0800 Subject: [PATCH 18/73] summary_ranges --- README.md | 1 + summary_ranges/summary_ranges.go | 36 ++++++++++++++++++++++++++++++++ 2 files changed, 37 insertions(+) create mode 100644 summary_ranges/summary_ranges.go diff --git a/README.md b/README.md index bbce49c..aaf189f 100644 --- a/README.md +++ b/README.md @@ -184,6 +184,7 @@ Golang solution for leetcode. For each problem, there is a simple *_test.go to t #### [225. Implement Stack using Queues](https://github.com/hitzzc/go-leetcode/tree/master/implement_stack_using_queues) #### [226. Invert Binary Tree](https://github.com/hitzzc/go-leetcode/tree/master/invert_binary_tree) #### [227. Basic Calculator II](https://github.com/hitzzc/go-leetcode/tree/master/basic_calculator_II) +#### [228. Summary Ranges](https://github.com/hitzzc/go-leetcode/tree/master/summary_ranges) diff --git a/summary_ranges/summary_ranges.go b/summary_ranges/summary_ranges.go new file mode 100644 index 0000000..01750ec --- /dev/null +++ b/summary_ranges/summary_ranges.go @@ -0,0 +1,36 @@ +package summary_ranges + +import ( + "strconv" +) + +func summaryRanges(nums []int) []string { + var ret []string + if len(nums) == 0 { + return ret + } + if len(nums) == 1 { + return []string{strconv.Itoa(nums[0])} + } + var i int + var j int = 1 + for ; j < len(nums); j++ { + if nums[j] == nums[j-1]+1 { + continue + } + if nums[j] != nums[j-1]+1 { + if j-1 == i { + ret = append(ret, strconv.Itoa(nums[i])) + } else { + ret = append(ret, strconv.Itoa(nums[i])+"->"+strconv.Itoa(nums[j-1])) + } + i = j + } + } + if j-1 == i { + ret = append(ret, strconv.Itoa(nums[i])) + } else { + ret = append(ret, strconv.Itoa(nums[i])+"->"+strconv.Itoa(nums[j-1])) + } + return ret +} From c83db740077967cc3e513f16274f29b416eb683a Mon Sep 17 00:00:00 2001 From: zczou Date: Mon, 17 Oct 2016 23:55:39 +0800 Subject: [PATCH 19/73] majority_element_II --- README.md | 1 + majority_element_II/majority_element_II.go | 37 ++++++++++++++++++++++ 2 files changed, 38 insertions(+) create mode 100644 majority_element_II/majority_element_II.go diff --git a/README.md b/README.md index aaf189f..e401341 100644 --- a/README.md +++ b/README.md @@ -185,6 +185,7 @@ Golang solution for leetcode. For each problem, there is a simple *_test.go to t #### [226. Invert Binary Tree](https://github.com/hitzzc/go-leetcode/tree/master/invert_binary_tree) #### [227. Basic Calculator II](https://github.com/hitzzc/go-leetcode/tree/master/basic_calculator_II) #### [228. Summary Ranges](https://github.com/hitzzc/go-leetcode/tree/master/summary_ranges) +#### [229. Majority Element II](https://github.com/hitzzc/go-leetcode/tree/master/majority_element_II) diff --git a/majority_element_II/majority_element_II.go b/majority_element_II/majority_element_II.go new file mode 100644 index 0000000..fa8d5c7 --- /dev/null +++ b/majority_element_II/majority_element_II.go @@ -0,0 +1,37 @@ +package majority_element_II + +func majorityElement(nums []int) []int { + var m, n, cm, cn int + for i := range nums { + if nums[i] == m { + cm++ + } else if nums[i] == n { + cn++ + } else if cm == 0 { + m = nums[i] + cm++ + } else if cn == 0 { + n = nums[i] + cn++ + } else { + cm-- + cn-- + } + } + cm, cn = 0, 0 + for i := range nums { + if nums[i] == m { + cm++ + } else if nums[i] == n { + cn++ + } + } + var ret []int + if cm > len(nums)/3 { + ret = append(ret, m) + } + if cn > len(nums)/3 { + ret = append(ret, n) + } + return ret +} From 3f4f6288a0e5b276b0b0fd02881cb8dc314db158 Mon Sep 17 00:00:00 2001 From: zczou Date: Tue, 18 Oct 2016 11:13:51 +0800 Subject: [PATCH 20/73] kth_smallest_element_in_a_BST --- README.md | 2 +- .../kth_smallest_element_in_a_BST.go | 28 +++++++++++++++++++ 2 files changed, 29 insertions(+), 1 deletion(-) create mode 100644 kth_smallest_element_in_a_BST/kth_smallest_element_in_a_BST.go diff --git a/README.md b/README.md index e401341..3a7d742 100644 --- a/README.md +++ b/README.md @@ -186,7 +186,7 @@ Golang solution for leetcode. For each problem, there is a simple *_test.go to t #### [227. Basic Calculator II](https://github.com/hitzzc/go-leetcode/tree/master/basic_calculator_II) #### [228. Summary Ranges](https://github.com/hitzzc/go-leetcode/tree/master/summary_ranges) #### [229. Majority Element II](https://github.com/hitzzc/go-leetcode/tree/master/majority_element_II) - +#### [230. Kth Smallest Element in a BST](https://github.com/hitzzc/go-leetcode/tree/master/kth_smallest_element_in_a_BST) diff --git a/kth_smallest_element_in_a_BST/kth_smallest_element_in_a_BST.go b/kth_smallest_element_in_a_BST/kth_smallest_element_in_a_BST.go new file mode 100644 index 0000000..0964931 --- /dev/null +++ b/kth_smallest_element_in_a_BST/kth_smallest_element_in_a_BST.go @@ -0,0 +1,28 @@ +package kth_smallest_element_in_a_BST + +type TreeNode struct { + Val int + Left *TreeNode + Right *TreeNode +} + +func kthSmallest(root *TreeNode, k int) int { + if root == nil { + return 0 + } + left := helper(root.Left) + if left == k-1 { + return root.Val + } + if left > k-1 { + return kthSmallest(root.Left, k) + } + return kthSmallest(root.Right, k-1-left) +} + +func helper(root *TreeNode) int { + if root == nil { + return 0 + } + return 1 + helper(root.Left) + helper(root.Right) +} From da618fafddce21642d50c0ed7547ae2771a37802 Mon Sep 17 00:00:00 2001 From: zczou Date: Tue, 18 Oct 2016 11:17:47 +0800 Subject: [PATCH 21/73] README.m --- README.md | 1 + power_of_two/power_of_two.go | 14 ++++++++++++++ 2 files changed, 15 insertions(+) create mode 100644 power_of_two/power_of_two.go diff --git a/README.md b/README.md index 3a7d742..5619d95 100644 --- a/README.md +++ b/README.md @@ -187,6 +187,7 @@ Golang solution for leetcode. For each problem, there is a simple *_test.go to t #### [228. Summary Ranges](https://github.com/hitzzc/go-leetcode/tree/master/summary_ranges) #### [229. Majority Element II](https://github.com/hitzzc/go-leetcode/tree/master/majority_element_II) #### [230. Kth Smallest Element in a BST](https://github.com/hitzzc/go-leetcode/tree/master/kth_smallest_element_in_a_BST) +#### [231. Power of Two](https://github.com/hitzzc/go-leetcode/tree/master/power_of_two) diff --git a/power_of_two/power_of_two.go b/power_of_two/power_of_two.go new file mode 100644 index 0000000..c044746 --- /dev/null +++ b/power_of_two/power_of_two.go @@ -0,0 +1,14 @@ +package power_of_two + +func isPowerOfTwo(n int) bool { + if n < 1 { + return false + } + for n > 1 { + if n&1 != 0 { + return false + } + n >>= 1 + } + return true +} From c45380a2167e1f484eaa2a8228faa35b3c564ef7 Mon Sep 17 00:00:00 2001 From: zczou Date: Tue, 18 Oct 2016 11:26:56 +0800 Subject: [PATCH 22/73] implement_queue_using_stacks --- README.md | 1 + .../implement_queue_using_stacks.cpp | 39 +++++++++++++++++++ 2 files changed, 40 insertions(+) create mode 100644 implement_queue_using_stacks/implement_queue_using_stacks.cpp diff --git a/README.md b/README.md index 5619d95..41e1551 100644 --- a/README.md +++ b/README.md @@ -188,6 +188,7 @@ Golang solution for leetcode. For each problem, there is a simple *_test.go to t #### [229. Majority Element II](https://github.com/hitzzc/go-leetcode/tree/master/majority_element_II) #### [230. Kth Smallest Element in a BST](https://github.com/hitzzc/go-leetcode/tree/master/kth_smallest_element_in_a_BST) #### [231. Power of Two](https://github.com/hitzzc/go-leetcode/tree/master/power_of_two) +#### [232. Implement Queue using Stacks](https://github.com/hitzzc/go-leetcode/tree/master/implement_queue_using_stacks) diff --git a/implement_queue_using_stacks/implement_queue_using_stacks.cpp b/implement_queue_using_stacks/implement_queue_using_stacks.cpp new file mode 100644 index 0000000..383a295 --- /dev/null +++ b/implement_queue_using_stacks/implement_queue_using_stacks.cpp @@ -0,0 +1,39 @@ +#include +using namespace std; + +class Queue { +public: + stack push_stack; + stack pop_stack; + // Push element x to the back of queue. + void push(int x) { + push_stack.push(x); + } + + // Removes the element from in front of queue. + void pop(void) { + if (pop_stack.empty()){ + while (!push_stack.empty()) { + pop_stack.push(push_stack.top()); + push_stack.pop(); + } + } + pop_stack.pop(); + } + + // Get the front element. + int peek(void) { + if (pop_stack.empty()){ + while (!push_stack.empty()) { + pop_stack.push(push_stack.top()); + push_stack.pop(); + } + } + return pop_stack.top(); + } + + // Return whether the queue is empty. + bool empty(void) { + return pop_stack.empty() && push_stack.empty(); + } +}; \ No newline at end of file From 041262ec9ac49670ecf1dcd42a63db4ab636c088 Mon Sep 17 00:00:00 2001 From: zczou Date: Tue, 18 Oct 2016 12:43:05 +0800 Subject: [PATCH 23/73] palindrome_lined_list --- README.md | 1 + .../palindrome_lined_list.go | 36 +++++++++++++++++++ 2 files changed, 37 insertions(+) create mode 100644 palindrome_lined_list/palindrome_lined_list.go diff --git a/README.md b/README.md index 41e1551..3caf9ba 100644 --- a/README.md +++ b/README.md @@ -189,6 +189,7 @@ Golang solution for leetcode. For each problem, there is a simple *_test.go to t #### [230. Kth Smallest Element in a BST](https://github.com/hitzzc/go-leetcode/tree/master/kth_smallest_element_in_a_BST) #### [231. Power of Two](https://github.com/hitzzc/go-leetcode/tree/master/power_of_two) #### [232. Implement Queue using Stacks](https://github.com/hitzzc/go-leetcode/tree/master/implement_queue_using_stacks) +#### [234. Palindrome Linked List](https://github.com/hitzzc/go-leetcode/tree/master/palindrome_lined_list) diff --git a/palindrome_lined_list/palindrome_lined_list.go b/palindrome_lined_list/palindrome_lined_list.go new file mode 100644 index 0000000..f1a136d --- /dev/null +++ b/palindrome_lined_list/palindrome_lined_list.go @@ -0,0 +1,36 @@ +package palindrome_lined_list + +type ListNode struct { + Val int + Next *ListNode +} + +func isPalindrome(head *ListNode) bool { + slow, fast := head, head + for fast != nil && fast.Next != nil { + slow = slow.Next + fast = fast.Next.Next + } + head2 := reverse(slow) + for ; head != nil && head2 != nil; head, head2 = head.Next, head2.Next { + if head.Val != head2.Val { + return false + } + } + return true +} + +func reverse(head *ListNode) (newHead *ListNode) { + var pre *ListNode + cur := head + for cur != nil { + tmp := cur.Next + cur.Next = pre + pre = cur + if tmp == nil { + break + } + cur = tmp + } + return cur +} From f9c8c630981a8459666413a23c5e062efd202dac Mon Sep 17 00:00:00 2001 From: zczou Date: Tue, 18 Oct 2016 14:09:01 +0800 Subject: [PATCH 24/73] lowest_common_ancestor --- README.md | 2 + ...ommon_ancestor_of_a_binary_search_tree.cpp | 17 +++++++ ...owest_common_ancestor_of_a_binary_tree.cpp | 48 +++++++++++++++++++ 3 files changed, 67 insertions(+) create mode 100644 lowest_common_ancestor_of_a_binary_search_tree/lowest_common_ancestor_of_a_binary_search_tree.cpp create mode 100644 lowest_common_ancestor_of_a_binary_tree/lowest_common_ancestor_of_a_binary_tree.cpp diff --git a/README.md b/README.md index 3caf9ba..142fb12 100644 --- a/README.md +++ b/README.md @@ -190,6 +190,8 @@ Golang solution for leetcode. For each problem, there is a simple *_test.go to t #### [231. Power of Two](https://github.com/hitzzc/go-leetcode/tree/master/power_of_two) #### [232. Implement Queue using Stacks](https://github.com/hitzzc/go-leetcode/tree/master/implement_queue_using_stacks) #### [234. Palindrome Linked List](https://github.com/hitzzc/go-leetcode/tree/master/palindrome_lined_list) +#### [235. Lowest Common Ancestor of a Binary Search Tree](https://github.com/hitzzc/go-leetcode/tree/master/lowest_common_ancestor_of_a_binary_search_tree) +#### [235. Lowest Common Ancestor of a Binary Tree](https://github.com/hitzzc/go-leetcode/tree/master/lowest_common_ancestor_of_a_binary_tree) diff --git a/lowest_common_ancestor_of_a_binary_search_tree/lowest_common_ancestor_of_a_binary_search_tree.cpp b/lowest_common_ancestor_of_a_binary_search_tree/lowest_common_ancestor_of_a_binary_search_tree.cpp new file mode 100644 index 0000000..1f19911 --- /dev/null +++ b/lowest_common_ancestor_of_a_binary_search_tree/lowest_common_ancestor_of_a_binary_search_tree.cpp @@ -0,0 +1,17 @@ +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 (root == NULL || p->val >= root->val && q->val <= root->val || p->val <= root->val && q->val >= root->val) + return root; + if (p->val <= root->val) + return lowestCommonAncestor(root->left, p, q); + return lowestCommonAncestor(root->right, p, q); + } +}; \ No newline at end of file diff --git a/lowest_common_ancestor_of_a_binary_tree/lowest_common_ancestor_of_a_binary_tree.cpp b/lowest_common_ancestor_of_a_binary_tree/lowest_common_ancestor_of_a_binary_tree.cpp new file mode 100644 index 0000000..1a8314e --- /dev/null +++ b/lowest_common_ancestor_of_a_binary_tree/lowest_common_ancestor_of_a_binary_tree.cpp @@ -0,0 +1,48 @@ +#include +using namespace std; + +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) { + vector path_p = {root}; + this->searchNode(root, p, path_p); + vector path_q = {root}; + this->searchNode(root, q, path_q); + int idx = path_p.size()= 0; --idx) { + if (path_p[idx] == path_q[idx]) return path_p[idx]; + } + return NULL; + } + + bool searchNode(TreeNode* root, TreeNode* target, vector& path) { + if (root == target) { + return true; + } + if (root->left == NULL && root->right == NULL) { + return false; + } + if (root->left != NULL){ + path.push_back(root->left); + if (searchNode(root->left, target, path)){ + return true; + } + path.pop_back(); + } + if (root->right != NULL){ + path.push_back(root->right); + if (searchNode(root->right, target, path)){ + return true; + } + path.pop_back(); + } + return false; + } +}; \ No newline at end of file From 7e0c24777a81ed121d1ba33f2460949006249ce3 Mon Sep 17 00:00:00 2001 From: zczou Date: Tue, 18 Oct 2016 14:17:43 +0800 Subject: [PATCH 25/73] delete_node_in_a_linked_list --- README.md | 3 ++- .../delete_node_in_a_linked_list.cpp | 20 +++++++++++++++++++ 2 files changed, 22 insertions(+), 1 deletion(-) create mode 100644 delete_node_in_a_linked_list/delete_node_in_a_linked_list.cpp diff --git a/README.md b/README.md index 142fb12..a9fa390 100644 --- a/README.md +++ b/README.md @@ -191,7 +191,8 @@ Golang solution for leetcode. For each problem, there is a simple *_test.go to t #### [232. Implement Queue using Stacks](https://github.com/hitzzc/go-leetcode/tree/master/implement_queue_using_stacks) #### [234. Palindrome Linked List](https://github.com/hitzzc/go-leetcode/tree/master/palindrome_lined_list) #### [235. Lowest Common Ancestor of a Binary Search Tree](https://github.com/hitzzc/go-leetcode/tree/master/lowest_common_ancestor_of_a_binary_search_tree) -#### [235. Lowest Common Ancestor of a Binary Tree](https://github.com/hitzzc/go-leetcode/tree/master/lowest_common_ancestor_of_a_binary_tree) +#### [236. Lowest Common Ancestor of a Binary Tree](https://github.com/hitzzc/go-leetcode/tree/master/lowest_common_ancestor_of_a_binary_tree) +#### [237. Delete Node in a Linked List](https://github.com/hitzzc/go-leetcode/tree/master/delete_node_in_a_linked_list) diff --git a/delete_node_in_a_linked_list/delete_node_in_a_linked_list.cpp b/delete_node_in_a_linked_list/delete_node_in_a_linked_list.cpp new file mode 100644 index 0000000..d5db91a --- /dev/null +++ b/delete_node_in_a_linked_list/delete_node_in_a_linked_list.cpp @@ -0,0 +1,20 @@ +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode(int x) : val(x), left(NULL), right(NULL) {} +}; + +class Solution { +public: + void deleteNode(ListNode* node) { + while (node->next != NULL) { + node->val = node->next->val; + if (node->next->next == NULL) + node->next = NULL; + else + node = node->next; + } + return; + } +}; \ No newline at end of file From de6ab40f4ca9a46ca1bdabe1f37a243c3bad1948 Mon Sep 17 00:00:00 2001 From: zczou Date: Wed, 19 Oct 2016 13:05:37 +0800 Subject: [PATCH 26/73] product_of_array_except_self --- README.md | 1 + .../product_of_array_except_self.go | 18 ++++++++++++++++++ 2 files changed, 19 insertions(+) create mode 100644 product_of_array_except_self/product_of_array_except_self.go diff --git a/README.md b/README.md index a9fa390..8838ce9 100644 --- a/README.md +++ b/README.md @@ -193,6 +193,7 @@ Golang solution for leetcode. For each problem, there is a simple *_test.go to t #### [235. Lowest Common Ancestor of a Binary Search Tree](https://github.com/hitzzc/go-leetcode/tree/master/lowest_common_ancestor_of_a_binary_search_tree) #### [236. Lowest Common Ancestor of a Binary Tree](https://github.com/hitzzc/go-leetcode/tree/master/lowest_common_ancestor_of_a_binary_tree) #### [237. Delete Node in a Linked List](https://github.com/hitzzc/go-leetcode/tree/master/delete_node_in_a_linked_list) +#### [238. product of array except self](https://github.com/hitzzc/go-leetcode/tree/master/product_of_array_except_self) diff --git a/product_of_array_except_self/product_of_array_except_self.go b/product_of_array_except_self/product_of_array_except_self.go new file mode 100644 index 0000000..87cad2e --- /dev/null +++ b/product_of_array_except_self/product_of_array_except_self.go @@ -0,0 +1,18 @@ +package product_of_array_except_self + +func productExceptSelf(nums []int) []int { + ret := make([]int, len(nums)) + left := 1 + right := 1 + for i := 0; i < len(nums); i++ { + if i <= (len(nums)-1)/2 { + ret[i] = 1 + ret[len(nums)-i-1] = 1 + } + ret[len(nums)-i-1] *= right + ret[i] *= left + left *= nums[i] + right *= nums[len(nums)-i-1] + } + return ret +} From 1cc60e30b86e39e231d2650eaf06f689e5515dfc Mon Sep 17 00:00:00 2001 From: zczou Date: Wed, 19 Oct 2016 13:13:58 +0800 Subject: [PATCH 27/73] sliding_window_maximum --- README.md | 2 ++ .../sliding_window_maximum.go | 19 +++++++++++++++++++ 2 files changed, 21 insertions(+) create mode 100644 sliding_window_maximum/sliding_window_maximum.go diff --git a/README.md b/README.md index 8838ce9..5f70d2d 100644 --- a/README.md +++ b/README.md @@ -194,6 +194,8 @@ Golang solution for leetcode. For each problem, there is a simple *_test.go to t #### [236. Lowest Common Ancestor of a Binary Tree](https://github.com/hitzzc/go-leetcode/tree/master/lowest_common_ancestor_of_a_binary_tree) #### [237. Delete Node in a Linked List](https://github.com/hitzzc/go-leetcode/tree/master/delete_node_in_a_linked_list) #### [238. product of array except self](https://github.com/hitzzc/go-leetcode/tree/master/product_of_array_except_self) +#### [239. Sliding Window Maximum](https://github.com/hitzzc/go-leetcode/tree/master/sliding_window_maximum) + diff --git a/sliding_window_maximum/sliding_window_maximum.go b/sliding_window_maximum/sliding_window_maximum.go new file mode 100644 index 0000000..0f07185 --- /dev/null +++ b/sliding_window_maximum/sliding_window_maximum.go @@ -0,0 +1,19 @@ +package sliding_window_maximum + +func maxSlidingWindow(nums []int, k int) []int { + ret := []int{} + idxArray := []int{} + for i := range nums { + for len(idxArray) != 0 && idxArray[0] <= i-k { + idxArray = idxArray[1:] + } + j := len(idxArray) - 1 + for ; j >= 0 && nums[idxArray[j]] <= nums[i]; j-- { + } + idxArray = append(idxArray[:j+1], i) + if i >= k-1 { + ret = append(ret, nums[idxArray[0]]) + } + } + return ret +} From cd90839bd0dbc782ac8034b397b47dac9defc5f5 Mon Sep 17 00:00:00 2001 From: zczou Date: Wed, 19 Oct 2016 14:19:59 +0800 Subject: [PATCH 28/73] search_a_2D_matrix_II --- README.md | 1 + .../search_a_2D_matrix_II.go | 20 +++++++++++++++++++ 2 files changed, 21 insertions(+) create mode 100644 search_a_2D_matrix_II/search_a_2D_matrix_II.go diff --git a/README.md b/README.md index 5f70d2d..bb19907 100644 --- a/README.md +++ b/README.md @@ -195,6 +195,7 @@ Golang solution for leetcode. For each problem, there is a simple *_test.go to t #### [237. Delete Node in a Linked List](https://github.com/hitzzc/go-leetcode/tree/master/delete_node_in_a_linked_list) #### [238. product of array except self](https://github.com/hitzzc/go-leetcode/tree/master/product_of_array_except_self) #### [239. Sliding Window Maximum](https://github.com/hitzzc/go-leetcode/tree/master/sliding_window_maximum) +#### [240. Search a 2D Matrix II](https://github.com/hitzzc/go-leetcode/tree/master/search_a_2D_matrix_II) diff --git a/search_a_2D_matrix_II/search_a_2D_matrix_II.go b/search_a_2D_matrix_II/search_a_2D_matrix_II.go new file mode 100644 index 0000000..b759200 --- /dev/null +++ b/search_a_2D_matrix_II/search_a_2D_matrix_II.go @@ -0,0 +1,20 @@ +package search_a_2D_matrix_II + +func searchMatrix(matrix [][]int, target int) bool { + if len(matrix) == 0 || len(matrix[0]) == 0 { + return false + } + row, col := 0, len(matrix[0])-1 + for row <= len(matrix)-1 && col >= 0 { + if matrix[row][col] == target { + return true + } + for row <= len(matrix)-1 && matrix[row][col] < target { + row++ + } + for col >= 0 && matrix[row][col] > target { + col-- + } + } + return false +} From 469d86c5ea60701d840a79eed580d2f817c01052 Mon Sep 17 00:00:00 2001 From: zczou Date: Wed, 19 Oct 2016 15:24:36 +0800 Subject: [PATCH 29/73] fix bug --- search_a_2D_matrix_II/search_a_2D_matrix_II.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/search_a_2D_matrix_II/search_a_2D_matrix_II.go b/search_a_2D_matrix_II/search_a_2D_matrix_II.go index b759200..54f76e3 100644 --- a/search_a_2D_matrix_II/search_a_2D_matrix_II.go +++ b/search_a_2D_matrix_II/search_a_2D_matrix_II.go @@ -9,10 +9,10 @@ func searchMatrix(matrix [][]int, target int) bool { if matrix[row][col] == target { return true } - for row <= len(matrix)-1 && matrix[row][col] < target { + for row <= len(matrix)-1 && col >= 0 && matrix[row][col] < target { row++ } - for col >= 0 && matrix[row][col] > target { + for row <= len(matrix)-1 && col >= 0 && matrix[row][col] > target { col-- } } From 60cf4ccc9e600e58fba8ef2c7999adce81d607e5 Mon Sep 17 00:00:00 2001 From: zczou Date: Thu, 20 Oct 2016 16:25:33 +0800 Subject: [PATCH 30/73] different_ways_to_add_parentheses --- README.md | 1 + .../different_ways_to_add_parentheses.go | 40 +++++++++++++++++++ 2 files changed, 41 insertions(+) create mode 100644 different_ways_to_add_parentheses/different_ways_to_add_parentheses.go diff --git a/README.md b/README.md index bb19907..6b3fa03 100644 --- a/README.md +++ b/README.md @@ -196,6 +196,7 @@ Golang solution for leetcode. For each problem, there is a simple *_test.go to t #### [238. product of array except self](https://github.com/hitzzc/go-leetcode/tree/master/product_of_array_except_self) #### [239. Sliding Window Maximum](https://github.com/hitzzc/go-leetcode/tree/master/sliding_window_maximum) #### [240. Search a 2D Matrix II](https://github.com/hitzzc/go-leetcode/tree/master/search_a_2D_matrix_II) +#### [241. Different Ways to Add Parentheses](https://github.com/hitzzc/go-leetcode/tree/master/different_ways_to_add_parentheses) diff --git a/different_ways_to_add_parentheses/different_ways_to_add_parentheses.go b/different_ways_to_add_parentheses/different_ways_to_add_parentheses.go new file mode 100644 index 0000000..fac5722 --- /dev/null +++ b/different_ways_to_add_parentheses/different_ways_to_add_parentheses.go @@ -0,0 +1,40 @@ +package different_ways_to_add_parentheses + +import ( + "strconv" +) + +func diffWaysToCompute(input string) []int { + return helper(input, map[string][]int{}) +} + +func helper(input string, cache map[string][]int) []int { + if v, ok := cache[input]; ok { + return v + } + ret := []int{} + for i := range input { + if input[i] == '+' || input[i] == '-' || input[i] == '*' { + left := helper(input[:i], cache) + right := helper(input[i+1:], cache) + for j := range left { + for k := range right { + switch input[i] { + case '+': + ret = append(ret, left[j]+right[k]) + case '-': + ret = append(ret, left[j]-right[k]) + case '*': + ret = append(ret, left[j]*right[k]) + } + } + } + } + } + if len(ret) == 0 { + num, _ := strconv.Atoi(input) + ret = append(ret, num) + } + cache[input] = ret + return ret +} From e59bc065befffe9cdb34f8a119d602374634372c Mon Sep 17 00:00:00 2001 From: zczou Date: Thu, 20 Oct 2016 17:45:40 +0800 Subject: [PATCH 31/73] valid_anagram --- README.md | 1 + valid_anagram/valid_anagram.go | 22 ++++++++++++++++++++++ 2 files changed, 23 insertions(+) create mode 100644 valid_anagram/valid_anagram.go diff --git a/README.md b/README.md index 6b3fa03..959ae1d 100644 --- a/README.md +++ b/README.md @@ -197,6 +197,7 @@ Golang solution for leetcode. For each problem, there is a simple *_test.go to t #### [239. Sliding Window Maximum](https://github.com/hitzzc/go-leetcode/tree/master/sliding_window_maximum) #### [240. Search a 2D Matrix II](https://github.com/hitzzc/go-leetcode/tree/master/search_a_2D_matrix_II) #### [241. Different Ways to Add Parentheses](https://github.com/hitzzc/go-leetcode/tree/master/different_ways_to_add_parentheses) +#### [242. Valid Anagram](https://github.com/hitzzc/go-leetcode/tree/master/valid_anagram) diff --git a/valid_anagram/valid_anagram.go b/valid_anagram/valid_anagram.go new file mode 100644 index 0000000..c0c96ce --- /dev/null +++ b/valid_anagram/valid_anagram.go @@ -0,0 +1,22 @@ +package valid_anagram + +import ( + "sort" +) + +func isAnagram(s string, t string) bool { + if len(s) != len(t) { + return false + } + m := [26]int{} + for i := range s { + m[int(s[i]-'a')]++ + m[int(t[i]-'a')]-- + } + for i := range m { + if m[i] != 0 { + return false + } + } + return true +} From b3457d02a2e633be4307631efe7f62f3815714c1 Mon Sep 17 00:00:00 2001 From: zczou Date: Thu, 20 Oct 2016 18:20:25 +0800 Subject: [PATCH 32/73] binary_tree_paths --- README.md | 1 + binary_tree_paths/binary_tree_paths.go | 51 ++++++++++++++++++++++++++ 2 files changed, 52 insertions(+) create mode 100644 binary_tree_paths/binary_tree_paths.go diff --git a/README.md b/README.md index 959ae1d..e01caa9 100644 --- a/README.md +++ b/README.md @@ -198,6 +198,7 @@ Golang solution for leetcode. For each problem, there is a simple *_test.go to t #### [240. Search a 2D Matrix II](https://github.com/hitzzc/go-leetcode/tree/master/search_a_2D_matrix_II) #### [241. Different Ways to Add Parentheses](https://github.com/hitzzc/go-leetcode/tree/master/different_ways_to_add_parentheses) #### [242. Valid Anagram](https://github.com/hitzzc/go-leetcode/tree/master/valid_anagram) +#### [257. Binary Tree Paths](https://github.com/hitzzc/go-leetcode/tree/master/binary_tree_paths) diff --git a/binary_tree_paths/binary_tree_paths.go b/binary_tree_paths/binary_tree_paths.go new file mode 100644 index 0000000..f718c7b --- /dev/null +++ b/binary_tree_paths/binary_tree_paths.go @@ -0,0 +1,51 @@ +package binary_tree_paths + +import ( + "strconv" +) + +type TreeNode struct { + Val int + Left *TreeNode + Right *TreeNode +} + +type solution struct { + path []*TreeNode + ret []string +} + +func binaryTreePaths(root *TreeNode) []string { + if root == nil { + return []string{} + } + s := &solution{path: []*TreeNode{root}} + s.helper() + return s.ret +} + +func (this *solution) helper() { + if len(this.path) == 0 { + return + } + root := this.path[len(this.path)-1] + if root.Left == nil && root.Right == nil { + s := strconv.Itoa(this.path[0].Val) + for i := 1; i < len(this.path); i++ { + s += "->" + strconv.Itoa(this.path[i].Val) + } + this.ret = append(this.ret, s) + return + } + if root.Left != nil { + this.path = append(this.path, root.Left) + this.helper() + this.path = this.path[:len(this.path)-1] + } + if root.Right != nil { + this.path = append(this.path, root.Right) + this.helper() + this.path = this.path[:len(this.path)-1] + } + return +} From 0371950582b0e47bf07b01ab9abe1ef8435feea9 Mon Sep 17 00:00:00 2001 From: zczou Date: Thu, 20 Oct 2016 18:25:50 +0800 Subject: [PATCH 33/73] add_digits --- README.md | 1 + add_digits/add_digits.go | 5 +++++ 2 files changed, 6 insertions(+) create mode 100644 add_digits/add_digits.go diff --git a/README.md b/README.md index e01caa9..e0d8b37 100644 --- a/README.md +++ b/README.md @@ -199,6 +199,7 @@ Golang solution for leetcode. For each problem, there is a simple *_test.go to t #### [241. Different Ways to Add Parentheses](https://github.com/hitzzc/go-leetcode/tree/master/different_ways_to_add_parentheses) #### [242. Valid Anagram](https://github.com/hitzzc/go-leetcode/tree/master/valid_anagram) #### [257. Binary Tree Paths](https://github.com/hitzzc/go-leetcode/tree/master/binary_tree_paths) +#### [258. Add Digits](https://github.com/hitzzc/go-leetcode/tree/master/add_digits) diff --git a/add_digits/add_digits.go b/add_digits/add_digits.go new file mode 100644 index 0000000..ac24340 --- /dev/null +++ b/add_digits/add_digits.go @@ -0,0 +1,5 @@ +package add_digits + +func addDigits(num int) int { + return (num-1)%9 + 1 +} From 7dd5716e84520837e66efda25cce893b199ffce5 Mon Sep 17 00:00:00 2001 From: zczou Date: Fri, 21 Oct 2016 00:14:31 +0800 Subject: [PATCH 34/73] single_number_III --- README.md | 1 + single_number_III/single_number_III.go | 20 ++++++++++++++++++++ 2 files changed, 21 insertions(+) create mode 100644 single_number_III/single_number_III.go diff --git a/README.md b/README.md index e0d8b37..3daa7a5 100644 --- a/README.md +++ b/README.md @@ -200,6 +200,7 @@ Golang solution for leetcode. For each problem, there is a simple *_test.go to t #### [242. Valid Anagram](https://github.com/hitzzc/go-leetcode/tree/master/valid_anagram) #### [257. Binary Tree Paths](https://github.com/hitzzc/go-leetcode/tree/master/binary_tree_paths) #### [258. Add Digits](https://github.com/hitzzc/go-leetcode/tree/master/add_digits) +#### [260. Single Number III](https://github.com/hitzzc/go-leetcode/tree/master/single_number_III) diff --git a/single_number_III/single_number_III.go b/single_number_III/single_number_III.go new file mode 100644 index 0000000..0f5a5e8 --- /dev/null +++ b/single_number_III/single_number_III.go @@ -0,0 +1,20 @@ +package single_number_III + +func singleNumber(nums []int) []int { + var allox int + for i := range nums { + allox ^= nums[i] + } + mask := 1 + for ; mask&allox == 0; mask <<= 1 { + } + var ret1, ret2 int + for i := range nums { + if nums[i]&mask != 0 { + ret1 ^= nums[i] + } else { + ret2 ^= nums[i] + } + } + return []int{ret1, ret2} +} From 476a8804cd1befddc4be517a773e00b2ffc3e2e1 Mon Sep 17 00:00:00 2001 From: zczou Date: Fri, 21 Oct 2016 00:20:04 +0800 Subject: [PATCH 35/73] ugly_number --- README.md | 1 + ugly_number/ugly_number.go | 17 +++++++++++++++++ 2 files changed, 18 insertions(+) create mode 100644 ugly_number/ugly_number.go diff --git a/README.md b/README.md index 3daa7a5..8d2a8f3 100644 --- a/README.md +++ b/README.md @@ -201,6 +201,7 @@ Golang solution for leetcode. For each problem, there is a simple *_test.go to t #### [257. Binary Tree Paths](https://github.com/hitzzc/go-leetcode/tree/master/binary_tree_paths) #### [258. Add Digits](https://github.com/hitzzc/go-leetcode/tree/master/add_digits) #### [260. Single Number III](https://github.com/hitzzc/go-leetcode/tree/master/single_number_III) +#### [263. Ugly Number](https://github.com/hitzzc/go-leetcode/tree/master/ugly_number) diff --git a/ugly_number/ugly_number.go b/ugly_number/ugly_number.go new file mode 100644 index 0000000..9bced7d --- /dev/null +++ b/ugly_number/ugly_number.go @@ -0,0 +1,17 @@ +package ugly_number + +func isUgly(num int) bool { + if num == 0 { + return false + } + for ; num%2 == 0; num /= 2 { + } + for ; num%3 == 0; num /= 3 { + } + for ; num%5 == 0; num /= 5 { + } + if num == 1 { + return true + } + return false +} From 7c449628d4b7838c6f9aa4bea326190d456c5fc0 Mon Sep 17 00:00:00 2001 From: zczou Date: Fri, 21 Oct 2016 17:52:41 +0800 Subject: [PATCH 36/73] ugly_number_II --- README.md | 1 + ugly_number_II/ugly_number_II.go | 30 ++++++++++++++++++++++++++++++ 2 files changed, 31 insertions(+) create mode 100644 ugly_number_II/ugly_number_II.go diff --git a/README.md b/README.md index 8d2a8f3..c60181b 100644 --- a/README.md +++ b/README.md @@ -202,6 +202,7 @@ Golang solution for leetcode. For each problem, there is a simple *_test.go to t #### [258. Add Digits](https://github.com/hitzzc/go-leetcode/tree/master/add_digits) #### [260. Single Number III](https://github.com/hitzzc/go-leetcode/tree/master/single_number_III) #### [263. Ugly Number](https://github.com/hitzzc/go-leetcode/tree/master/ugly_number) +#### [264. Ugly Number II](https://github.com/hitzzc/go-leetcode/tree/master/ugly_number_II) diff --git a/ugly_number_II/ugly_number_II.go b/ugly_number_II/ugly_number_II.go new file mode 100644 index 0000000..24f1cf6 --- /dev/null +++ b/ugly_number_II/ugly_number_II.go @@ -0,0 +1,30 @@ +package ugly_number_II + +func nthUglyNumber(n int) int { + if n == 1 { + return 1 + } + records := []int{1} + i, j, k := 0, 0, 0 + for len(records) < n { + next := min(2*records[i], min(3*records[j], 5*records[k])) + if next == 2*records[i] { + i++ + } + if next == 3*records[j] { + j++ + } + if next == 5*records[k] { + k++ + } + records = append(records, next) + } + return records[len(records)-1] +} + +func min(i, j int) int { + if i < j { + return i + } + return j +} From ac71818c16453c5a3a764f012e0e7ec75943e901 Mon Sep 17 00:00:00 2001 From: zczou Date: Fri, 21 Oct 2016 18:21:04 +0800 Subject: [PATCH 37/73] missing_number --- README.md | 1 + missing_number/missing_number.go | 17 +++++++++++++++++ 2 files changed, 18 insertions(+) create mode 100644 missing_number/missing_number.go diff --git a/README.md b/README.md index c60181b..19f0373 100644 --- a/README.md +++ b/README.md @@ -203,6 +203,7 @@ Golang solution for leetcode. For each problem, there is a simple *_test.go to t #### [260. Single Number III](https://github.com/hitzzc/go-leetcode/tree/master/single_number_III) #### [263. Ugly Number](https://github.com/hitzzc/go-leetcode/tree/master/ugly_number) #### [264. Ugly Number II](https://github.com/hitzzc/go-leetcode/tree/master/ugly_number_II) +#### [268. Missing Number](https://github.com/hitzzc/go-leetcode/tree/master/missing_number) diff --git a/missing_number/missing_number.go b/missing_number/missing_number.go new file mode 100644 index 0000000..389b07b --- /dev/null +++ b/missing_number/missing_number.go @@ -0,0 +1,17 @@ +package missing_number + +func missingNumber(nums []int) int { + ret := 0 + for i := range nums { + ret ^= nums[i] ^ (i + 1) + } + return ret +} + +func missingNumberI(nums []int) int { + ret := 0 + for i := range nums { + ret += i + 1 - nums[i] + } + return ret +} From 65793014c670aeb30ae39b35a7a708f928b47cd8 Mon Sep 17 00:00:00 2001 From: zczou Date: Sat, 22 Oct 2016 18:17:29 +0800 Subject: [PATCH 38/73] perfect_squares --- README.md | 2 ++ first_bad_version/first_bad_version.cpp | 21 +++++++++++++++++++++ perfect_squares/perfect_squares.cpp | 20 ++++++++++++++++++++ 3 files changed, 43 insertions(+) create mode 100644 first_bad_version/first_bad_version.cpp create mode 100644 perfect_squares/perfect_squares.cpp diff --git a/README.md b/README.md index 19f0373..25483a2 100644 --- a/README.md +++ b/README.md @@ -204,6 +204,8 @@ Golang solution for leetcode. For each problem, there is a simple *_test.go to t #### [263. Ugly Number](https://github.com/hitzzc/go-leetcode/tree/master/ugly_number) #### [264. Ugly Number II](https://github.com/hitzzc/go-leetcode/tree/master/ugly_number_II) #### [268. Missing Number](https://github.com/hitzzc/go-leetcode/tree/master/missing_number) +#### [278. First Bad Version](https://github.com/hitzzc/go-leetcode/tree/master/missing_number) +#### [279. Perfect Squares](https://github.com/hitzzc/go-leetcode/tree/master/perfect_squares) diff --git a/first_bad_version/first_bad_version.cpp b/first_bad_version/first_bad_version.cpp new file mode 100644 index 0000000..abcee50 --- /dev/null +++ b/first_bad_version/first_bad_version.cpp @@ -0,0 +1,21 @@ +bool isBadVersion(int version); + +class Solution { +public: + int firstBadVersion(int n) { + int i = 1; + int j = n; + int ret; + while (i <= j) { + int mid = i + (j-i)/2; + if (isBadVersion(mid)) { + j = mid; + ret = mid; + }else { + i= mid+1; + ret = mid+1; + } + } + return ret; + } +}; \ No newline at end of file diff --git a/perfect_squares/perfect_squares.cpp b/perfect_squares/perfect_squares.cpp new file mode 100644 index 0000000..168c406 --- /dev/null +++ b/perfect_squares/perfect_squares.cpp @@ -0,0 +1,20 @@ +class Solution { +public: + int numSquares(int n) { + if ( n<=0 ) return 0; + static vector dp(1, 0); + if (dp.size() >n) return dp[n]; + for (int i = dp.size(); i <= n; ++i) { + int m = n; + for (int j = 1; i-j*j>=0; ++j) { + m = min(m, dp[i-j*j]+1); + } + dp.push_back(m); + } + return dp[n]; + } + int min(int i, int j) { + if (i < j) return i; + return j; + } +}; \ No newline at end of file From e14c84dd20484001b5dc24796017550ec35588d9 Mon Sep 17 00:00:00 2001 From: zczou Date: Sat, 22 Oct 2016 21:36:15 +0800 Subject: [PATCH 39/73] 2 problems --- README.md | 2 + .../expression_add_operators.cpp | 39 +++++++++++++++++++ move_zeroes/move_zeroes.cpp | 16 ++++++++ 3 files changed, 57 insertions(+) create mode 100644 expression_add_operators/expression_add_operators.cpp create mode 100644 move_zeroes/move_zeroes.cpp diff --git a/README.md b/README.md index 25483a2..12a97bd 100644 --- a/README.md +++ b/README.md @@ -206,6 +206,8 @@ Golang solution for leetcode. For each problem, there is a simple *_test.go to t #### [268. Missing Number](https://github.com/hitzzc/go-leetcode/tree/master/missing_number) #### [278. First Bad Version](https://github.com/hitzzc/go-leetcode/tree/master/missing_number) #### [279. Perfect Squares](https://github.com/hitzzc/go-leetcode/tree/master/perfect_squares) +#### [282. Expression Add Operators](https://github.com/hitzzc/go-leetcode/tree/master/expression_add_operators) +#### [283. Move Zeroes](https://github.com/hitzzc/go-leetcode/tree/master/expression_add_operators) diff --git a/expression_add_operators/expression_add_operators.cpp b/expression_add_operators/expression_add_operators.cpp new file mode 100644 index 0000000..63314d4 --- /dev/null +++ b/expression_add_operators/expression_add_operators.cpp @@ -0,0 +1,39 @@ +class Solution { +public: + vector addOperators(string num, int target) { + vector results; + DFS(num, target, 0, "", 0, " ", 0, results); + return results; + } + + void DFS(string& num, int target, int idx, string solution, long long current_val, string pre_op, long long pre_val, vector& results) { + if (current_val == target && idx == num.size()) { + results.push_back(solution); + return; + } + if (idx == num.size()) return; + string n; + long long v = 0; + for (int i = idx; i < num.size(); ++i) { + if (n =="0") { + return; + } + n += num[i]; + v = 10*v + num[i] - '0'; + if (solution.size() == 0) { + DFS(num, target, i+1, n, v, " ", 0, results); + }else { + DFS(num, target, i+1, solution + "+" + n, current_val + v, "+", v, results); + DFS(num, target, i+1, solution + "-" + n, current_val - v, "-", v, results); + if (pre_op == "+") { + DFS(num, target, i+1, solution + "*" + n, current_val-pre_val+pre_val*v, pre_op, pre_val*v, results); + }else if (pre_op == "-") { + DFS(num, target, i+1, solution + "*" + n, current_val+pre_val-pre_val*v, pre_op, pre_val*v, results); + }else { + DFS(num, target, i+1, solution + "*" + n, current_val*v, "*", v, results); + } + } + } + return; + } +}; \ No newline at end of file diff --git a/move_zeroes/move_zeroes.cpp b/move_zeroes/move_zeroes.cpp new file mode 100644 index 0000000..7729b88 --- /dev/null +++ b/move_zeroes/move_zeroes.cpp @@ -0,0 +1,16 @@ +class Solution { +public: + void moveZeroes(vector& nums) { + int j = 0; + int tmp; + for (int i = 0; i < nums.size(); ++i){ + if (nums[i] != 0){ + tmp = nums[i]; + nums[i] = nums[j]; + nums[j] = tmp; + j++; + } + } + return; + } +}; \ No newline at end of file From 1d03761307d3034a88f6c3695d026a1d152b0691 Mon Sep 17 00:00:00 2001 From: zczou Date: Sat, 22 Oct 2016 22:55:32 +0800 Subject: [PATCH 40/73] 2 problems --- README.md | 2 + .../find_the_duplicate_number.cpp | 18 +++++++ peeking_iterator/peeking_iterator.cpp | 50 +++++++++++++++++++ 3 files changed, 70 insertions(+) create mode 100644 find_the_duplicate_number/find_the_duplicate_number.cpp create mode 100644 peeking_iterator/peeking_iterator.cpp diff --git a/README.md b/README.md index 12a97bd..fae961c 100644 --- a/README.md +++ b/README.md @@ -208,6 +208,8 @@ Golang solution for leetcode. For each problem, there is a simple *_test.go to t #### [279. Perfect Squares](https://github.com/hitzzc/go-leetcode/tree/master/perfect_squares) #### [282. Expression Add Operators](https://github.com/hitzzc/go-leetcode/tree/master/expression_add_operators) #### [283. Move Zeroes](https://github.com/hitzzc/go-leetcode/tree/master/expression_add_operators) +#### [284. Peeking Iterator](https://github.com/hitzzc/go-leetcode/tree/master/peeking_iterator) +#### [287. Find the Duplicate Number](https://github.com/hitzzc/go-leetcode/tree/master/find_the_duplicate_number) diff --git a/find_the_duplicate_number/find_the_duplicate_number.cpp b/find_the_duplicate_number/find_the_duplicate_number.cpp new file mode 100644 index 0000000..10ca39f --- /dev/null +++ b/find_the_duplicate_number/find_the_duplicate_number.cpp @@ -0,0 +1,18 @@ +class Solution { +public: + int findDuplicate(vector& nums) { + int i = 0; + int j = 0; + while (true) { + i = nums[i]; + j = nums[nums[j]]; + if (i == j) break; + } + j = 0; + while (i != j) { + i = nums[i]; + j = nums[j]; + } + return i; + } +}; \ No newline at end of file diff --git a/peeking_iterator/peeking_iterator.cpp b/peeking_iterator/peeking_iterator.cpp new file mode 100644 index 0000000..43c5cb5 --- /dev/null +++ b/peeking_iterator/peeking_iterator.cpp @@ -0,0 +1,50 @@ +// Below is the interface for Iterator, which is already defined for you. +// **DO NOT** modify the interface for Iterator. +class Iterator { + struct Data; + Data* data; +public: + Iterator(const vector& nums); + Iterator(const Iterator& iter); + virtual ~Iterator(); + // Returns the next element in the iteration. + int next(); + // Returns true if the iteration has more elements. + bool hasNext() const; +}; + + +class PeekingIterator : public Iterator { + int cache; + bool is_peeked; +public: + PeekingIterator(const vector& nums) : Iterator(nums), is_peeked(false) { + + } + + // Returns the next element in the iteration without advancing the iterator. + int peek() { + if (!is_peeked) { + cache = Iterator::next(); + is_peeked = true; + } + return cache; + } + + // hasNext() and next() should behave the same as in the Iterator interface. + // Override them if needed. + int next() { + if (is_peeked) { + is_peeked = false; + return cache; + } + return Iterator::next(); + } + + bool hasNext() const { + if (is_peeked) { + return true; + } + return Iterator::hasNext(); + } +}; \ No newline at end of file From b8dd7f9b2dc3d4479550236470c3e9e3ffecd56c Mon Sep 17 00:00:00 2001 From: zczou Date: Sun, 23 Oct 2016 10:10:59 +0800 Subject: [PATCH 41/73] word_pattern --- README.md | 1 + word_pattern/word_pattern.cpp | 34 ++++++++++++++++++++++++++++++++++ 2 files changed, 35 insertions(+) create mode 100644 word_pattern/word_pattern.cpp diff --git a/README.md b/README.md index fae961c..02ce0c6 100644 --- a/README.md +++ b/README.md @@ -210,6 +210,7 @@ Golang solution for leetcode. For each problem, there is a simple *_test.go to t #### [283. Move Zeroes](https://github.com/hitzzc/go-leetcode/tree/master/expression_add_operators) #### [284. Peeking Iterator](https://github.com/hitzzc/go-leetcode/tree/master/peeking_iterator) #### [287. Find the Duplicate Number](https://github.com/hitzzc/go-leetcode/tree/master/find_the_duplicate_number) +#### [290. Word Pattern](https://github.com/hitzzc/go-leetcode/tree/master/word_pattern) diff --git a/word_pattern/word_pattern.cpp b/word_pattern/word_pattern.cpp new file mode 100644 index 0000000..53bdff6 --- /dev/null +++ b/word_pattern/word_pattern.cpp @@ -0,0 +1,34 @@ +#include +#include +#include +using namespace std; + +class Solution { +public: + bool wordPattern(string pattern, string str) { + unordered_map pattern_to_str; + unordered_map str_to_pattern; + int i = 0; + int start = 0; + for (int j = 0; j <= str.size(); ++j){ + if (i >= pattern.size()) return false; + if (j == str.size() || str[j] == ' ') { + string sub = str.substr(start, j-start); + if (pattern_to_str.count(pattern[i]) == 0 && str_to_pattern.count(sub) == 0) { + pattern_to_str[pattern[i]] = sub; + str_to_pattern[sub] = pattern[i]; + }else if (pattern_to_str.count(pattern[i]) != 0 && str_to_pattern.count(sub) != 0) { + if (pattern_to_str[pattern[i]] != sub || str_to_pattern[sub] != pattern[i]) { + return false; + } + }else { + return false; + } + ++i; + start = j+1; + } + } + if (i != pattern.size()) return false; + return true; + } +}; \ No newline at end of file From 8ed511d3f14df717c82b79a4b1a206859c2c99f6 Mon Sep 17 00:00:00 2001 From: zczou Date: Mon, 24 Oct 2016 00:54:08 +0800 Subject: [PATCH 42/73] 2 problems --- README.md | 2 + .../find_median_from_data_stream.cpp | 104 ++++++++++++++++++ nim_game/nim_game.cpp | 6 + 3 files changed, 112 insertions(+) create mode 100644 find_median_from_data_stream/find_median_from_data_stream.cpp create mode 100644 nim_game/nim_game.cpp diff --git a/README.md b/README.md index 02ce0c6..a79cd2b 100644 --- a/README.md +++ b/README.md @@ -211,6 +211,8 @@ Golang solution for leetcode. For each problem, there is a simple *_test.go to t #### [284. Peeking Iterator](https://github.com/hitzzc/go-leetcode/tree/master/peeking_iterator) #### [287. Find the Duplicate Number](https://github.com/hitzzc/go-leetcode/tree/master/find_the_duplicate_number) #### [290. Word Pattern](https://github.com/hitzzc/go-leetcode/tree/master/word_pattern) +#### [292. Nim Game](https://github.com/hitzzc/go-leetcode/tree/master/nim_game) +#### [295. Find Median from Data Stream](https://github.com/hitzzc/go-leetcode/tree/master/find_median_from_data_stream) diff --git a/find_median_from_data_stream/find_median_from_data_stream.cpp b/find_median_from_data_stream/find_median_from_data_stream.cpp new file mode 100644 index 0000000..79c14bc --- /dev/null +++ b/find_median_from_data_stream/find_median_from_data_stream.cpp @@ -0,0 +1,104 @@ +#include +#include +using namespace std; + +class Heap { +private: + vector array; + int (*compare) (int, int); + void adjust(int idx) { + int largest = idx; + if (2*idx+1 < array.size() && compare(array[2*idx+1], array[idx])) + largest = 2*idx+1; + if (2*idx+2 < array.size() && compare(array[2*idx+2],array[largest])) + largest = 2*idx+2; + if (largest != idx) { + int tmp = array[idx]; + array[idx] = array[largest]; + array[largest] = tmp; + adjust(largest); + } + return; + } +public: + Heap(int (*compare) (int, int)): compare(compare) {} + void push(int val) { + array.push_back(val); + for (int i = array.size()/2 - 1; i >= 0; --i){ + adjust(i); + } + } + void print() { + for (auto val: array) + cout << "print\t" << val << endl; + } + int pop() { + int ret = array[0]; + array[0] = array.back(); + array.pop_back(); + adjust(0); + return ret; + } + int empty() { + return array.empty(); + } + int size() { + return array.size(); + } + int top() { + return array[0]; + } +}; + +int max(int i, int j) { + if (i > j) return true; + return false; +} + +int min(int i, int j) { + if (i < j) return true; + return false; +} + +class MedianFinder { + Heap max_heap; + Heap min_heap; +public: + MedianFinder(): max_heap(Heap(max)), min_heap(Heap(min)){} + // Adds a number into the data structure. + void addNum(int num) { + if (max_heap.empty() || num <= max_heap.top()) { + max_heap.push(num); + }else { + min_heap.push(num); + } + if (max_heap.size() > min_heap.size()+1){ + int top = max_heap.pop(); + min_heap.push(top); + } + if (min_heap.size() > max_heap.size()) { + int top = min_heap.pop(); + max_heap.push(top); + } + return; + } + + // Returns the median of current data stream + double findMedian() { + if (max_heap.size() == min_heap.size()) + return ((max_heap.top()+min_heap.top())/2.0); + if (max_heap.size() > min_heap.size()) + return max_heap.top(); + return min_heap.top(); + } +}; + +int main() { + MedianFinder finder; + finder.addNum(-1); + finder.addNum(-2); + finder.addNum(-3); + finder.addNum(-4); + finder.addNum(-5); + return 0; +} diff --git a/nim_game/nim_game.cpp b/nim_game/nim_game.cpp new file mode 100644 index 0000000..1d1992c --- /dev/null +++ b/nim_game/nim_game.cpp @@ -0,0 +1,6 @@ +class Solution { +public: + bool canWinNim(int n) { + return !(n%4 == 0); + } +}; \ No newline at end of file From 541086c47fc31756538ff6709bb46760ea42741b Mon Sep 17 00:00:00 2001 From: zczou Date: Mon, 24 Oct 2016 12:04:31 +0800 Subject: [PATCH 43/73] using stl container --- .../find_median_from_data_stream.cpp | 19 +++++++++---------- 1 file changed, 9 insertions(+), 10 deletions(-) diff --git a/find_median_from_data_stream/find_median_from_data_stream.cpp b/find_median_from_data_stream/find_median_from_data_stream.cpp index 79c14bc..5052422 100644 --- a/find_median_from_data_stream/find_median_from_data_stream.cpp +++ b/find_median_from_data_stream/find_median_from_data_stream.cpp @@ -1,5 +1,7 @@ #include #include +#include +#include using namespace std; class Heap { @@ -61,10 +63,9 @@ int min(int i, int j) { } class MedianFinder { - Heap max_heap; - Heap min_heap; + priority_queue max_heap; + priority_queue, greater> min_heap; public: - MedianFinder(): max_heap(Heap(max)), min_heap(Heap(min)){} // Adds a number into the data structure. void addNum(int num) { if (max_heap.empty() || num <= max_heap.top()) { @@ -73,11 +74,13 @@ class MedianFinder { min_heap.push(num); } if (max_heap.size() > min_heap.size()+1){ - int top = max_heap.pop(); + int top = max_heap.top(); + max_heap.pop(); min_heap.push(top); } if (min_heap.size() > max_heap.size()) { - int top = min_heap.pop(); + int top = min_heap.top(); + min_heap.pop(); max_heap.push(top); } return; @@ -85,11 +88,7 @@ class MedianFinder { // Returns the median of current data stream double findMedian() { - if (max_heap.size() == min_heap.size()) - return ((max_heap.top()+min_heap.top())/2.0); - if (max_heap.size() > min_heap.size()) - return max_heap.top(); - return min_heap.top(); + return max_heap.size() == min_heap.size() ? (max_heap.top()+min_heap.top())/2.0 : max_heap.top(); } }; From 7baa42921ca2234c0cd031a0db6f96f8b3c3ef01 Mon Sep 17 00:00:00 2001 From: zczou Date: Mon, 24 Oct 2016 13:55:32 +0800 Subject: [PATCH 44/73] 2 problems --- README.md | 2 + bulls_and_cows/bulls_and_cows.cpp | 28 ++++++++++++ .../serialize_and_deserialize_binary_tree.cpp | 44 +++++++++++++++++++ 3 files changed, 74 insertions(+) create mode 100644 bulls_and_cows/bulls_and_cows.cpp create mode 100644 serialize_and_deserialize_binary_tree/serialize_and_deserialize_binary_tree.cpp diff --git a/README.md b/README.md index a79cd2b..ecbfdca 100644 --- a/README.md +++ b/README.md @@ -213,6 +213,8 @@ Golang solution for leetcode. For each problem, there is a simple *_test.go to t #### [290. Word Pattern](https://github.com/hitzzc/go-leetcode/tree/master/word_pattern) #### [292. Nim Game](https://github.com/hitzzc/go-leetcode/tree/master/nim_game) #### [295. Find Median from Data Stream](https://github.com/hitzzc/go-leetcode/tree/master/find_median_from_data_stream) +#### [297. Serialize and Deserialize Binary Tree](https://github.com/hitzzc/go-leetcode/tree/master/serialize_and_deserialize_binary_tree) +#### [299. Bulls and Cows](https://github.com/hitzzc/go-leetcode/tree/master/bulls_and_cows) diff --git a/bulls_and_cows/bulls_and_cows.cpp b/bulls_and_cows/bulls_and_cows.cpp new file mode 100644 index 0000000..936ccdb --- /dev/null +++ b/bulls_and_cows/bulls_and_cows.cpp @@ -0,0 +1,28 @@ +#include +using namespace std; + +class Solution { +public: + string getHint(string secret, string guess) { + int secret_array[10] = {0}; + int bull = 0; + for (int i = 0; i < secret.size(); ++i) { + if (secret[i] == guess[i]) { + ++bull; + continue; + } + ++secret_array[secret[i]-'0']; + } + int cow = 0; + for (int i = 0; i < guess.size(); ++i) { + if (secret[i] == guess[i]) { + continue; + } + if (secret_array[guess[i]-'0'] !=0 ){ + ++cow; + --secret_array[guess[i]-'0']; + } + } + return to_string(bull) + "A" + to_string(cow) + "B"; + } +}; \ No newline at end of file diff --git a/serialize_and_deserialize_binary_tree/serialize_and_deserialize_binary_tree.cpp b/serialize_and_deserialize_binary_tree/serialize_and_deserialize_binary_tree.cpp new file mode 100644 index 0000000..9a85c7b --- /dev/null +++ b/serialize_and_deserialize_binary_tree/serialize_and_deserialize_binary_tree.cpp @@ -0,0 +1,44 @@ +#include +using namespace std; + +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode(int x) : val(x), left(NULL), right(NULL) {} +}; + +class Codec { +public: + string serialize(TreeNode* root) { + if (root == NULL) { + return "null"; + } + string ret = to_string(root->val); + ret += "," + serialize(root->left); + ret += "," + serialize(root->right); + return ret; + } + + TreeNode* deserialize(string data) { + int idx = 0; + return helper(data, idx); + } + + TreeNode* helper(string& data, int& idx) { + int start = idx; + for (; idx < data.size(); ++idx) { + if (data[idx] == ',') { + break; + } + } + string sub = data.substr(start, idx-start); + ++idx; + if (sub == "null") return NULL; + TreeNode* node = new TreeNode(stoi(sub)); + if (idx == data.size()) return node; + node->left = helper(data, idx); + node->right = helper(data, idx); + return node; + } +}; \ No newline at end of file From 6eb479c7e29308609c206026da2aee5603fe2618 Mon Sep 17 00:00:00 2001 From: zczou Date: Mon, 24 Oct 2016 15:19:37 +0800 Subject: [PATCH 45/73] longest_increasing_subsequence --- README.md | 1 + .../longest_increasing_subsequence.cpp | 57 +++++++++++++++++++ 2 files changed, 58 insertions(+) create mode 100644 longest_increasing_subsequence/longest_increasing_subsequence.cpp diff --git a/README.md b/README.md index ecbfdca..e59e589 100644 --- a/README.md +++ b/README.md @@ -215,6 +215,7 @@ Golang solution for leetcode. For each problem, there is a simple *_test.go to t #### [295. Find Median from Data Stream](https://github.com/hitzzc/go-leetcode/tree/master/find_median_from_data_stream) #### [297. Serialize and Deserialize Binary Tree](https://github.com/hitzzc/go-leetcode/tree/master/serialize_and_deserialize_binary_tree) #### [299. Bulls and Cows](https://github.com/hitzzc/go-leetcode/tree/master/bulls_and_cows) +#### [300. Longest Increasing Subsequence](https://github.com/hitzzc/go-leetcode/tree/master/longest_increasing_subsequence) diff --git a/longest_increasing_subsequence/longest_increasing_subsequence.cpp b/longest_increasing_subsequence/longest_increasing_subsequence.cpp new file mode 100644 index 0000000..ce0830f --- /dev/null +++ b/longest_increasing_subsequence/longest_increasing_subsequence.cpp @@ -0,0 +1,57 @@ +#include +using namespace std; + +class Solution { +public: + int lengthOfLIS(vector& nums) { + if (nums.size() == 0) return 0; + int max = 1; + vector fn(nums.size(), 0); + fn[0] = 1; + for (int i = 0; i < nums.size(); ++i) { + for (int j = 0; j < i; ++j) { + if (nums[i] > nums[j] && fn[j]+1 > fn[i]) + fn[i] = fn[j]+1; + } + if (fn[i] > max) max = fn[i]; + } + return fn.back(); + } + + int lengthOfLIS2(vector& nums) { + if (nums.size() < 2) return nums.size(); + vector vec(1, nums[0]); + for (int i = 1; i < nums.size(); ++i) { + if (nums[i] > vec.back()) { + vec.push_back(nums[i]); + continue; + }else if (nums[i] == vec.back()) { + continue; + }else{ + int pos = binary_search(vec, nums[i]); + vec[pos] = nums[i]; + } + } + return vec.size(); + } + + int binary_search(vector& nums, int target) { + int start = 0; + int end = nums.size(); + int idx = -1; + int mid; + while (start < end) { + mid = start + (end-start)/2; + if (nums[mid] == target) { + return mid; + }else if (nums[mid] < target) { + idx = mid+1; + start = mid+1; + }else{ + idx = mid; + end = mid; + } + } + return idx; + } +}; \ No newline at end of file From e4783c46553ce7272c6387ff1e99ed9fb61d59c5 Mon Sep 17 00:00:00 2001 From: zczou Date: Tue, 25 Oct 2016 12:08:48 +0800 Subject: [PATCH 46/73] remove_invalid_parentheses --- README.md | 1 + .../remove_invalid_parentheses.cpp | 42 +++++++++++++++++++ 2 files changed, 43 insertions(+) create mode 100644 remove_invalid_parentheses/remove_invalid_parentheses.cpp diff --git a/README.md b/README.md index e59e589..deb8769 100644 --- a/README.md +++ b/README.md @@ -216,6 +216,7 @@ Golang solution for leetcode. For each problem, there is a simple *_test.go to t #### [297. Serialize and Deserialize Binary Tree](https://github.com/hitzzc/go-leetcode/tree/master/serialize_and_deserialize_binary_tree) #### [299. Bulls and Cows](https://github.com/hitzzc/go-leetcode/tree/master/bulls_and_cows) #### [300. Longest Increasing Subsequence](https://github.com/hitzzc/go-leetcode/tree/master/longest_increasing_subsequence) +#### [301. Remove Invalid Parentheses](https://github.com/hitzzc/go-leetcode/tree/master/remove_invalid_parentheses) diff --git a/remove_invalid_parentheses/remove_invalid_parentheses.cpp b/remove_invalid_parentheses/remove_invalid_parentheses.cpp new file mode 100644 index 0000000..4570489 --- /dev/null +++ b/remove_invalid_parentheses/remove_invalid_parentheses.cpp @@ -0,0 +1,42 @@ +#include +#include +using namespace std; + +class Solution { +public: + vector removeInvalidParentheses(string s) { + int left = 0; + int right = 0; + for (auto ch: s) { + if (ch == '(') ++left; + if (ch == ')') { + if (left > 0) --left; + else ++right; + } + } + vector results; + unordered_set unique; + DFS(s, 0, 0, left, right, "", results, unique); + return results; + } + + void DFS(string&s, int idx, int pair, int left, int right, string solution, vector& results, unordered_set& unique) { + if (idx == s.size()) { + if (left == 0 && right == 0 && pair == 0 && unique.find(solution) == unique.end()) { + results.push_back(solution); + unique.insert(solution); + } + return; + } + if (s[idx] == '(') { + if (left > 0) DFS(s, idx+1, pair, left-1, right, solution, results, unique); + DFS(s, idx+1, pair+1, left, right, solution+"(", results, unique); + }else if (s[idx] == ')') { + if (right > 0) DFS(s, idx+1, pair, left, right-1, solution, results, unique); + if (pair > 0) DFS(s, idx+1, pair-1, left, right, solution+")", results, unique); + }else { + DFS(s, idx+1, pair, left, right, solution+s[idx], results, unique); + } + return; + } +}; \ No newline at end of file From 5bc12ed0cada21e11f4567a12b6830302f1e78e5 Mon Sep 17 00:00:00 2001 From: zczou Date: Tue, 25 Oct 2016 12:57:17 +0800 Subject: [PATCH 47/73] 2 --- README.md | 3 +++ .../range_sum_query_2d_immutable.cpp | 21 +++++++++++++++++++ .../range_sum_query_immutable.cpp | 17 +++++++++++++++ 3 files changed, 41 insertions(+) create mode 100644 range_sum_query_2d_immutable/range_sum_query_2d_immutable.cpp create mode 100644 range_sum_query_immutable/range_sum_query_immutable.cpp diff --git a/README.md b/README.md index deb8769..4528d7c 100644 --- a/README.md +++ b/README.md @@ -217,6 +217,9 @@ Golang solution for leetcode. For each problem, there is a simple *_test.go to t #### [299. Bulls and Cows](https://github.com/hitzzc/go-leetcode/tree/master/bulls_and_cows) #### [300. Longest Increasing Subsequence](https://github.com/hitzzc/go-leetcode/tree/master/longest_increasing_subsequence) #### [301. Remove Invalid Parentheses](https://github.com/hitzzc/go-leetcode/tree/master/remove_invalid_parentheses) +#### [303. Range Sum Query - Immutable](https://github.com/hitzzc/go-leetcode/tree/master/range_sum_query_immutable) +#### [304. Range Sum Query 2D - Immutable](https://github.com/hitzzc/go-leetcode/tree/master/range_sum_query_immutable) + diff --git a/range_sum_query_2d_immutable/range_sum_query_2d_immutable.cpp b/range_sum_query_2d_immutable/range_sum_query_2d_immutable.cpp new file mode 100644 index 0000000..ab63562 --- /dev/null +++ b/range_sum_query_2d_immutable/range_sum_query_2d_immutable.cpp @@ -0,0 +1,21 @@ +#include +using namespace std; + +class NumMatrix { + vector> records; +public: + NumMatrix(vector> &matrix) { + int row = matrix.size(); + int col = row == 0 ? 0 : matrix[0].size(); + records = vector>(row+1, vector(col+1, 0)); + for (int i = 0; i < row; ++i) { + for (int j = 0; j < col; ++j) { + records[i+1][j+1] = records[i][j+1] + records[i+1][j] - records[i][j] + matrix[i][j]; + } + } + } + + int sumRegion(int row1, int col1, int row2, int col2) { + return records[row2+1][col2+1] - records[row2+1][col1] - records[row1][col2+1] + records[row1][col1]; + } +}; \ No newline at end of file diff --git a/range_sum_query_immutable/range_sum_query_immutable.cpp b/range_sum_query_immutable/range_sum_query_immutable.cpp new file mode 100644 index 0000000..96858f3 --- /dev/null +++ b/range_sum_query_immutable/range_sum_query_immutable.cpp @@ -0,0 +1,17 @@ +#include +using namespace std; + +class NumArray { + vector fn; +public: + NumArray(vector &nums): fn(vector(nums.size()+1)) { + fn[0] = 0; + for (int i = 0; i < nums.size(); ++i) { + fn[i+1] = fn[i] + nums[i]; + } + } + + int sumRange(int i, int j) { + return fn[j] - fn[i-1]; + } +}; \ No newline at end of file From e3bd6fd77152bc8c00ec3142e6e32d8412a984e8 Mon Sep 17 00:00:00 2001 From: zczou Date: Tue, 25 Oct 2016 17:02:55 +0800 Subject: [PATCH 48/73] 2 problem --- README.md | 2 + additive_number/additive_number.cpp | 30 ++++++++++++++ .../range_sum_query_mutable.cpp | 40 +++++++++++++++++++ 3 files changed, 72 insertions(+) create mode 100644 additive_number/additive_number.cpp create mode 100644 range_sum_query_mutable/range_sum_query_mutable.cpp diff --git a/README.md b/README.md index 4528d7c..c16776b 100644 --- a/README.md +++ b/README.md @@ -219,6 +219,8 @@ Golang solution for leetcode. For each problem, there is a simple *_test.go to t #### [301. Remove Invalid Parentheses](https://github.com/hitzzc/go-leetcode/tree/master/remove_invalid_parentheses) #### [303. Range Sum Query - Immutable](https://github.com/hitzzc/go-leetcode/tree/master/range_sum_query_immutable) #### [304. Range Sum Query 2D - Immutable](https://github.com/hitzzc/go-leetcode/tree/master/range_sum_query_immutable) +#### [306. Additive Number](https://github.com/hitzzc/go-leetcode/tree/master/additive_number) +#### [307. Range Sum Query - Mutable](https://github.com/hitzzc/go-leetcode/tree/master/range_sum_query_mutable) diff --git a/additive_number/additive_number.cpp b/additive_number/additive_number.cpp new file mode 100644 index 0000000..381b975 --- /dev/null +++ b/additive_number/additive_number.cpp @@ -0,0 +1,30 @@ +#include +using namespace std; + +class Solution { +public: + bool isAdditiveNumber(string num) { + return DFS(num, 0, 0, 0, 0); + } + + bool DFS(string& num, int start, int length, int first, int second) { + if (start == num.size()) { + if (length > 2) return true; + else return false; + } + int current_num = 0; + for (int i = start; i < num.size(); ++i) { + if (num[start] == '0' && i != start) break; + current_num = 10*current_num + num[i]-'0'; + if (length == 0) first = current_num; + else if (length == 1) second = current_num; + else if (current_num != first+second) continue; + else { + first = second; + second = current_num; + } + if (DFS(num, i+1, length+1, first, second)) return true; + } + return false; + } +}; \ No newline at end of file diff --git a/range_sum_query_mutable/range_sum_query_mutable.cpp b/range_sum_query_mutable/range_sum_query_mutable.cpp new file mode 100644 index 0000000..9a4df0a --- /dev/null +++ b/range_sum_query_mutable/range_sum_query_mutable.cpp @@ -0,0 +1,40 @@ +class NumArray { + vector records; + vector ori; +public: + NumArray(vector &nums): records(vector(nums.size()+1, 0)), ori(nums) { + for (int i = 0; i < nums.size(); ++i) { + add(i+1, nums[i]); + } + } + + void update(int i, int val) { + int diff = val - ori[i]; + ori[i] = val; + add(i+1, diff); + } + + int sumRange(int i, int j) { + return sum(j+1) - sum(i); + } + + void add(int x, int diff) { + while (x < records.size()) { + records[x] += diff; + x += lowbit(x); + } + } + + int sum(int x) { + int ret = 0; + while (x > 0) { + ret += records[x]; + x -= lowbit(x); + } + return ret; + } + + int lowbit(int n) { + return n&-n; + } +}; \ No newline at end of file From 71b7dd843fc333a80767fd9f738d7b51fa19f491 Mon Sep 17 00:00:00 2001 From: zczou Date: Thu, 27 Oct 2016 16:02:36 +0800 Subject: [PATCH 49/73] stock --- README.md | 5 ++++ .../best_time_to_buy_and_sell_stock.cpp | 14 +++++++++++ .../best_time_to_buy_and_sell_stock_II.cpp | 11 +++++++++ .../best_time_to_buy_and_sell_stock_III.cpp | 23 ++++++++++++++++++ .../best_time_to_buy_and_sell_stock_IV.cpp | 24 +++++++++++++++++++ ...me_to_buy_and_sell_stock_with_cooldown.cpp | 17 +++++++++++++ 6 files changed, 94 insertions(+) create mode 100644 best_time_to_buy_and_sell_stock/best_time_to_buy_and_sell_stock.cpp create mode 100644 best_time_to_buy_and_sell_stock_II/best_time_to_buy_and_sell_stock_II.cpp create mode 100644 best_time_to_buy_and_sell_stock_III/best_time_to_buy_and_sell_stock_III.cpp create mode 100644 best_time_to_buy_and_sell_stock_IV/best_time_to_buy_and_sell_stock_IV.cpp create mode 100644 best_time_to_buy_and_sell_stock_with_cooldown/best_time_to_buy_and_sell_stock_with_cooldown.cpp diff --git a/README.md b/README.md index c16776b..69f6106 100644 --- a/README.md +++ b/README.md @@ -107,6 +107,9 @@ Golang solution for leetcode. For each problem, there is a simple *_test.go to t #### [118. pascal's triangle](https://github.com/hitzzc/go-leetcode/tree/master/pascals_triangle) #### [119. pascal's triangle II](https://github.com/hitzzc/go-leetcode/tree/master/pascals_triangle_II) #### [120. triangle](https://github.com/hitzzc/go-leetcode/tree/master/triangle) +#### [121. Best Time to Buy and Sell Stock](https://github.com/hitzzc/go-leetcode/tree/master/best_time_to_buy_and_sell_stock) +#### [122. Best Time to Buy and Sell Stock II](https://github.com/hitzzc/go-leetcode/tree/master/best_time_to_buy_and_sell_stock_II) +#### [123. Best Time to Buy and Sell Stock III](https://github.com/hitzzc/go-leetcode/tree/master/best_time_to_buy_and_sell_stock_III) #### [124. binary tree maximum path sum](https://github.com/hitzzc/go-leetcode/tree/master/binary_tree_maximum_path_sum) #### [125. valid palindrome](https://github.com/hitzzc/go-leetcode/tree/master/valid_palindrome) #### [126. word ladder II](https://github.com/hitzzc/go-leetcode/tree/master/word_ladder_II) @@ -153,6 +156,7 @@ Golang solution for leetcode. For each problem, there is a simple *_test.go to t #### [174. Dungeon Game](https://github.com/hitzzc/go-leetcode/tree/master/dungeon_game) #### [179. Largest Number](https://github.com/hitzzc/go-leetcode/tree/master/largest_number) #### [187. Repeated DNA Sequences](https://github.com/hitzzc/go-leetcode/tree/master/repeated_dna_sequences) +#### [188. Best Time to Buy and Sell Stock IV](https://github.com/hitzzc/go-leetcode/tree/master/best_time_to_buy_and_sell_stock_IV) #### [189. Rotate Array](https://github.com/hitzzc/go-leetcode/tree/master/rotate_array) #### [190. Reverse Bits](https://github.com/hitzzc/go-leetcode/tree/master/reverse_bits) #### [191. Number of 1 Bits](https://github.com/hitzzc/go-leetcode/tree/master/number_of_1bits) @@ -221,6 +225,7 @@ Golang solution for leetcode. For each problem, there is a simple *_test.go to t #### [304. Range Sum Query 2D - Immutable](https://github.com/hitzzc/go-leetcode/tree/master/range_sum_query_immutable) #### [306. Additive Number](https://github.com/hitzzc/go-leetcode/tree/master/additive_number) #### [307. Range Sum Query - Mutable](https://github.com/hitzzc/go-leetcode/tree/master/range_sum_query_mutable) +#### [309. Best Time to Buy and Sell Stock with Cooldown](https://github.com/hitzzc/go-leetcode/tree/master/best_time_to_buy_and_sell_stock_with_cooldown) diff --git a/best_time_to_buy_and_sell_stock/best_time_to_buy_and_sell_stock.cpp b/best_time_to_buy_and_sell_stock/best_time_to_buy_and_sell_stock.cpp new file mode 100644 index 0000000..9137bd3 --- /dev/null +++ b/best_time_to_buy_and_sell_stock/best_time_to_buy_and_sell_stock.cpp @@ -0,0 +1,14 @@ +class Solution { +public: + int maxProfit(vector& prices) { + if (prices.size() == 0) return 0; + int min = prices[0]; + int max = 0; + for (int i = 1; i < prices.size(); ++i) { + int diff = prices[i] - min; + if (diff > max) max = diff; + if (prices[i] < min) min = prices[i]; + } + return max; + } +}; \ No newline at end of file diff --git a/best_time_to_buy_and_sell_stock_II/best_time_to_buy_and_sell_stock_II.cpp b/best_time_to_buy_and_sell_stock_II/best_time_to_buy_and_sell_stock_II.cpp new file mode 100644 index 0000000..82878e7 --- /dev/null +++ b/best_time_to_buy_and_sell_stock_II/best_time_to_buy_and_sell_stock_II.cpp @@ -0,0 +1,11 @@ +class Solution { +public: + int maxProfit(vector& prices) { + if (prices.size() == 0) return 0; + int ret = 0; + for (int i = 0; i < prices.size()-1; ++i) { + if (prices[i+1] > prices[i]) ret += prices[i+1] - prices[i]; + } + return ret; + } +}; \ No newline at end of file diff --git a/best_time_to_buy_and_sell_stock_III/best_time_to_buy_and_sell_stock_III.cpp b/best_time_to_buy_and_sell_stock_III/best_time_to_buy_and_sell_stock_III.cpp new file mode 100644 index 0000000..5e06006 --- /dev/null +++ b/best_time_to_buy_and_sell_stock_III/best_time_to_buy_and_sell_stock_III.cpp @@ -0,0 +1,23 @@ +class Solution { +public: + int maxProfit(vector& prices) { + if (prices.size() == 0) return 0; + vector fn1(prices.size(), 0); + vector fn2(prices.size(), 0); + int minV = prices[0]; + for (int i = 1; i < prices.size(); ++i) { + fn1[i] = max(fn1[i-1], prices[i]-minV); + minV = min(minV, prices[i]); + } + int maxV = prices[prices.size()-1]; + for (int i = prices.size()-2; i >= 0; --i) { + fn2[i] = max(fn2[i+1], maxV-prices[i]); + maxV = max(maxV, prices[i]); + } + int ret = 0; + for (int i = 0; i < fn1.size(); ++i) { + ret = max(ret, fn1[i] + fn2[i]); + } + return ret; + } +}; \ No newline at end of file diff --git a/best_time_to_buy_and_sell_stock_IV/best_time_to_buy_and_sell_stock_IV.cpp b/best_time_to_buy_and_sell_stock_IV/best_time_to_buy_and_sell_stock_IV.cpp new file mode 100644 index 0000000..ae98c2b --- /dev/null +++ b/best_time_to_buy_and_sell_stock_IV/best_time_to_buy_and_sell_stock_IV.cpp @@ -0,0 +1,24 @@ +class Solution { +public: + int maxProfit(int k, vector& prices) { + if (prices.size() < 2) return 0; + if (k > prices.size()/2) { + int ret = 0; + for (int i = 0; i < prices.size()-1; ++i) { + if (prices[i+1] - prices[i] > 0) ret += prices[i+1] - prices[i]; + } + return ret; + } + vector> dp(k+1, vector(prices.size()+1, 0)); + for (int i = 1; i <= k; ++i) { + int maxV = dp[i-1][0] - prices[0]; + for (int j = 1; j <= prices.size(); ++j) { + dp[i][j] = max(dp[i][j-1], maxV + prices[j-1]); + if (j < prices.size() && dp[i-1][j] - prices[j] > maxV) { + maxV = dp[i-1][j] - prices[j]; + } + } + } + return dp[k][prices.size()]; + } +}; \ No newline at end of file diff --git a/best_time_to_buy_and_sell_stock_with_cooldown/best_time_to_buy_and_sell_stock_with_cooldown.cpp b/best_time_to_buy_and_sell_stock_with_cooldown/best_time_to_buy_and_sell_stock_with_cooldown.cpp new file mode 100644 index 0000000..05880f3 --- /dev/null +++ b/best_time_to_buy_and_sell_stock_with_cooldown/best_time_to_buy_and_sell_stock_with_cooldown.cpp @@ -0,0 +1,17 @@ +class Solution { +public: + int maxProfit(vector& prices) { + if (prices.size() < 2) return 0; + int buy = -prices[0]; + int sell = -1; + int cold = 0; + int tmp; + for (int i = 1; i < prices.size(); ++i) { + tmp = buy; + buy = max(tmp, cold-prices[i]); + cold = max(cold, sell); + sell = tmp+prices[i]; + } + return max(sell, cold); + } +}; \ No newline at end of file From 3e1c0b7db61cf6422f10c3787f2dcd8f7ba50f5c Mon Sep 17 00:00:00 2001 From: zczou Date: Thu, 27 Oct 2016 16:24:47 +0800 Subject: [PATCH 50/73] minimum_height_trees --- README.md | 1 + minimum_height_trees/minimum_height_trees.cpp | 27 +++++++++++++++++++ 2 files changed, 28 insertions(+) create mode 100644 minimum_height_trees/minimum_height_trees.cpp diff --git a/README.md b/README.md index 69f6106..e7ee7d3 100644 --- a/README.md +++ b/README.md @@ -226,6 +226,7 @@ Golang solution for leetcode. For each problem, there is a simple *_test.go to t #### [306. Additive Number](https://github.com/hitzzc/go-leetcode/tree/master/additive_number) #### [307. Range Sum Query - Mutable](https://github.com/hitzzc/go-leetcode/tree/master/range_sum_query_mutable) #### [309. Best Time to Buy and Sell Stock with Cooldown](https://github.com/hitzzc/go-leetcode/tree/master/best_time_to_buy_and_sell_stock_with_cooldown) +#### [310. Minimum Height Trees](https://github.com/hitzzc/go-leetcode/tree/master/minimum_height_trees) diff --git a/minimum_height_trees/minimum_height_trees.cpp b/minimum_height_trees/minimum_height_trees.cpp new file mode 100644 index 0000000..cf7bbf4 --- /dev/null +++ b/minimum_height_trees/minimum_height_trees.cpp @@ -0,0 +1,27 @@ +class Solution { +public: + vector findMinHeightTrees(int n, vector>& edges) { + if (n <= 1) return {0}; + vector> graph(n); + for (auto& edge: edges) { + graph[edge.first].insert(edge.second); + graph[edge.second].insert(edge.first); + } + vector current; + for (int i = 0; i < graph.size(); ++i) { + if (graph[i].size() == 1) current.push_back(i); + } + while (true) { + vector next; + for (auto& node: current) { + for (auto& neighbor: graph[node]) { + graph[neighbor].erase(node); + if (graph[neighbor].size() == 1) next.push_back(neighbor); + } + } + if (next.size() == 0) break; + current.swap(next); + } + return current; + } +}; \ No newline at end of file From 473bb11ec62459377128af24f3bf831fd7db7f29 Mon Sep 17 00:00:00 2001 From: zczou Date: Sat, 29 Oct 2016 12:33:53 +0800 Subject: [PATCH 51/73] 2 problem --- README.md | 4 +++- burst_balloons/burst_balloons.cpp | 17 +++++++++++++++++ super_ugly_number/super_ugly_number.cpp | 17 +++++++++++++++++ 3 files changed, 37 insertions(+), 1 deletion(-) create mode 100644 burst_balloons/burst_balloons.cpp create mode 100644 super_ugly_number/super_ugly_number.cpp diff --git a/README.md b/README.md index e7ee7d3..a552929 100644 --- a/README.md +++ b/README.md @@ -226,7 +226,9 @@ Golang solution for leetcode. For each problem, there is a simple *_test.go to t #### [306. Additive Number](https://github.com/hitzzc/go-leetcode/tree/master/additive_number) #### [307. Range Sum Query - Mutable](https://github.com/hitzzc/go-leetcode/tree/master/range_sum_query_mutable) #### [309. Best Time to Buy and Sell Stock with Cooldown](https://github.com/hitzzc/go-leetcode/tree/master/best_time_to_buy_and_sell_stock_with_cooldown) -#### [310. Minimum Height Trees](https://github.com/hitzzc/go-leetcode/tree/master/minimum_height_trees) +#### [312. Burst Balloons](https://github.com/hitzzc/go-leetcode/tree/master/burst_balloons) +#### [313. Super Ugly Number](https://github.com/hitzzc/go-leetcode/tree/master/super_ugly_number) + diff --git a/burst_balloons/burst_balloons.cpp b/burst_balloons/burst_balloons.cpp new file mode 100644 index 0000000..3aaca1a --- /dev/null +++ b/burst_balloons/burst_balloons.cpp @@ -0,0 +1,17 @@ +class Solution { +public: + int maxCoins(vector& nums) { + nums.insert(nums.begin(), 1); + nums.push_back(1); + vector> matrix(nums.size(), vector(nums.size(), 0)); + for (int k = 2; k < nums.size(); ++k) { + for (int low = 0; low < nums.size()-k; ++low) { + int high = low+k; + for (int i = low+1; i < high; ++i) { + matrix[low][high] = max(matrix[low][high], nums[low]*nums[i]*nums[high] + matrix[low][i] + matrix[i][high]); + } + } + } + return matrix[0][matrix.size()-1]; + } +}; \ No newline at end of file diff --git a/super_ugly_number/super_ugly_number.cpp b/super_ugly_number/super_ugly_number.cpp new file mode 100644 index 0000000..b2a5cdc --- /dev/null +++ b/super_ugly_number/super_ugly_number.cpp @@ -0,0 +1,17 @@ +class Solution { +public: + int nthSuperUglyNumber(int n, vector& primes) { + vector dp(n, 1); + vector idxs(primes.size(), 0); + for (int i = 1; i < n; ++i) { + dp[i] = INT_MAX; + for (int idx = 0; idx < idxs.size(); ++idx) { + dp[i] = min(dp[i], primes[idx]*dp[idxs[idx]]); + } + for (int idx = 0; idx < idxs.size(); ++idx) { + if (dp[i] == primes[idx] * dp[idxs[idx]]) ++idxs[idx]; + } + } + return dp.back(); + } +}; \ No newline at end of file From b38dabe0c254b4d58914b7df0f320699d0015617 Mon Sep 17 00:00:00 2001 From: zczou Date: Sat, 29 Oct 2016 17:46:58 +0800 Subject: [PATCH 52/73] count_of_smaller_numbers_after_self --- README.md | 1 + .../count_of_smaller_numbers_after_self.cpp | 41 +++++++++++++++++++ 2 files changed, 42 insertions(+) create mode 100644 count_of_smaller_numbers_after_self/count_of_smaller_numbers_after_self.cpp diff --git a/README.md b/README.md index a552929..d056b14 100644 --- a/README.md +++ b/README.md @@ -228,6 +228,7 @@ Golang solution for leetcode. For each problem, there is a simple *_test.go to t #### [309. Best Time to Buy and Sell Stock with Cooldown](https://github.com/hitzzc/go-leetcode/tree/master/best_time_to_buy_and_sell_stock_with_cooldown) #### [312. Burst Balloons](https://github.com/hitzzc/go-leetcode/tree/master/burst_balloons) #### [313. Super Ugly Number](https://github.com/hitzzc/go-leetcode/tree/master/super_ugly_number) +#### [315. Count of Smaller Numbers After Self](https://github.com/hitzzc/go-leetcode/tree/master/count_of_smaller_numbers_after_self) diff --git a/count_of_smaller_numbers_after_self/count_of_smaller_numbers_after_self.cpp b/count_of_smaller_numbers_after_self/count_of_smaller_numbers_after_self.cpp new file mode 100644 index 0000000..0dd1151 --- /dev/null +++ b/count_of_smaller_numbers_after_self/count_of_smaller_numbers_after_self.cpp @@ -0,0 +1,41 @@ +class binary_index_tree { + vector array; +public: + binary_index_tree(int n): array(n+1, 0) {} + int lowbit(int x) { + return x & (-x); + } + int sum(int idx) { + int ret = 0; + while (idx > 0) { + ret += array[idx]; + idx -= lowbit(idx); + } + return ret; + } + void add(int idx, int val) { + while (idx < array.size()) { + array[idx] += val; + idx += lowbit(idx); + } + } +}; + +class Solution { +public: + vector countSmaller(vector& nums) { + vector sorted = nums; + sort(sorted.begin(), sorted.end()); + unordered_map mapping; + for (int i = 0; i < sorted.size(); ++i) { + mapping[sorted[i]] = i+1; + } + binary_index_tree my_bit(nums.size()); + vector ret(nums.size()); + for (int i = nums.size()-1; i >=0; --i) { + ret[i] = my_bit.sum(mapping[nums[i]]-1); + my_bit.add(mapping[nums[i]], 1); + } + return ret; + } +}; \ No newline at end of file From 8ad8ab58564e50a48d39bacdcd9701e1ce1a7a21 Mon Sep 17 00:00:00 2001 From: zczou Date: Sun, 30 Oct 2016 11:33:41 +0800 Subject: [PATCH 53/73] remove_duplicate_letters --- README.md | 1 + .../remove_duplicate_letters.cpp | 31 +++++++++++++++++++ 2 files changed, 32 insertions(+) create mode 100644 remove_duplicate_letters/remove_duplicate_letters.cpp diff --git a/README.md b/README.md index d056b14..02cc100 100644 --- a/README.md +++ b/README.md @@ -229,6 +229,7 @@ Golang solution for leetcode. For each problem, there is a simple *_test.go to t #### [312. Burst Balloons](https://github.com/hitzzc/go-leetcode/tree/master/burst_balloons) #### [313. Super Ugly Number](https://github.com/hitzzc/go-leetcode/tree/master/super_ugly_number) #### [315. Count of Smaller Numbers After Self](https://github.com/hitzzc/go-leetcode/tree/master/count_of_smaller_numbers_after_self) +#### [316. Remove Duplicate Letters](https://github.com/hitzzc/go-leetcode/tree/master/remove_duplicate_letters) diff --git a/remove_duplicate_letters/remove_duplicate_letters.cpp b/remove_duplicate_letters/remove_duplicate_letters.cpp new file mode 100644 index 0000000..f4b1cfc --- /dev/null +++ b/remove_duplicate_letters/remove_duplicate_letters.cpp @@ -0,0 +1,31 @@ +class Solution { +public: + string removeDuplicateLetters(string s) { + if (s.size() == 0) return ""; + unordered_map count; + for (int i = 0; i < s.size(); ++i) { + ++count[s[i]]; + } + unordered_set existed = {s[0]}; + vector vec = {s[0]}; + --count[s[0]]; + for (int i = 1; i < s.size(); ++i) { + --count[s[i]]; + if (existed.count(s[i]) == 0) { + while (!vec.empty()) { + char back = vec.back(); + if (back <= s[i] || count[back] == 0) break; + vec.pop_back(); + existed.erase(back); + } + vec.push_back(s[i]); + existed.insert(s[i]); + } + } + string ret; + for (auto ch: vec) { + ret += ch; + } + return ret; + } +}; \ No newline at end of file From 918a8934c6e3fbda52c465f746a54f9ecc9b7755 Mon Sep 17 00:00:00 2001 From: zczou Date: Sun, 30 Oct 2016 11:44:07 +0800 Subject: [PATCH 54/73] maximum_product_of_word_lengths --- README.md | 1 + .../maximum_product_of_word_lengths.cpp | 19 +++++++++++++++++++ 2 files changed, 20 insertions(+) create mode 100644 maximum_product_of_word_lengths/maximum_product_of_word_lengths.cpp diff --git a/README.md b/README.md index 02cc100..3a48328 100644 --- a/README.md +++ b/README.md @@ -230,6 +230,7 @@ Golang solution for leetcode. For each problem, there is a simple *_test.go to t #### [313. Super Ugly Number](https://github.com/hitzzc/go-leetcode/tree/master/super_ugly_number) #### [315. Count of Smaller Numbers After Self](https://github.com/hitzzc/go-leetcode/tree/master/count_of_smaller_numbers_after_self) #### [316. Remove Duplicate Letters](https://github.com/hitzzc/go-leetcode/tree/master/remove_duplicate_letters) +#### [318. Maximum Product of Word Lengths ](https://github.com/hitzzc/go-leetcode/tree/master/maximum_product_of_word_lengths) diff --git a/maximum_product_of_word_lengths/maximum_product_of_word_lengths.cpp b/maximum_product_of_word_lengths/maximum_product_of_word_lengths.cpp new file mode 100644 index 0000000..01ab5d4 --- /dev/null +++ b/maximum_product_of_word_lengths/maximum_product_of_word_lengths.cpp @@ -0,0 +1,19 @@ +class Solution { +public: + int maxProduct(vector& words) { + vector helper(words.size(), 0); + for (int i = 0; i < words.size(); ++i) { + for (auto& ch: words[i]) { + helper[i] |= 1 << (ch-'a'); + } + } + int ret = 0; + for (int i = 0; i < helper.size(); ++i) { + for (int j = i+1; j < helper.size(); ++j) { + if (helper[i] & helper[j]) continue; + if (words[i].size() * words[j].size() > ret) ret = words[i].size() * words[j].size(); + } + } + return ret; + } +}; \ No newline at end of file From 4f21847bed9e9e1107ab5fb580ca5a9f2cbf515a Mon Sep 17 00:00:00 2001 From: zczou Date: Sun, 30 Oct 2016 13:16:50 +0800 Subject: [PATCH 55/73] 3 problems --- README.md | 5 ++++- bulb_switcher/bulb_switcher.cpp | 10 ++++++++++ coin_change/coin_change.cpp | 13 +++++++++++++ power_of_three/power_of_three.cpp | 6 ++++++ 4 files changed, 33 insertions(+), 1 deletion(-) create mode 100644 bulb_switcher/bulb_switcher.cpp create mode 100644 coin_change/coin_change.cpp create mode 100644 power_of_three/power_of_three.cpp diff --git a/README.md b/README.md index 3a48328..57961a8 100644 --- a/README.md +++ b/README.md @@ -230,7 +230,10 @@ Golang solution for leetcode. For each problem, there is a simple *_test.go to t #### [313. Super Ugly Number](https://github.com/hitzzc/go-leetcode/tree/master/super_ugly_number) #### [315. Count of Smaller Numbers After Self](https://github.com/hitzzc/go-leetcode/tree/master/count_of_smaller_numbers_after_self) #### [316. Remove Duplicate Letters](https://github.com/hitzzc/go-leetcode/tree/master/remove_duplicate_letters) -#### [318. Maximum Product of Word Lengths ](https://github.com/hitzzc/go-leetcode/tree/master/maximum_product_of_word_lengths) +#### [318. Maximum Product of Word Lengths ](https://github.com/hitzzc/go-leetcode/tree/master/maximum_product_of_word_lengths) +#### [319. Bulb Switcher](https://github.com/hitzzc/go-leetcode/tree/master/bulb_switcher) +#### [322. Coin Change](https://github.com/hitzzc/go-leetcode/tree/master/coin_change) +#### [326. Power of Three](https://github.com/hitzzc/go-leetcode/tree/master/power_of_three) diff --git a/bulb_switcher/bulb_switcher.cpp b/bulb_switcher/bulb_switcher.cpp new file mode 100644 index 0000000..cc9b4e3 --- /dev/null +++ b/bulb_switcher/bulb_switcher.cpp @@ -0,0 +1,10 @@ +class Solution { +public: + int bulbSwitch(int n) { + int ret = 0; + for (int i = 1; i*i <= n; ++i) { + ++ret; + } + return ret; + } +}; \ No newline at end of file diff --git a/coin_change/coin_change.cpp b/coin_change/coin_change.cpp new file mode 100644 index 0000000..d1f175d --- /dev/null +++ b/coin_change/coin_change.cpp @@ -0,0 +1,13 @@ +class Solution { +public: + int coinChange(vector& coins, int amount) { + vector dp(amount+1, amount+1); + dp[0] = 0; + for (int i = 1; i < dp.size(); ++i) { + for (auto coin: coins) { + if (i >= coin) dp[i] = min(dp[i], dp[i-coin]+1); + } + } + return dp.back() == amount+1 ? -1: dp.back(); + } +}; \ No newline at end of file diff --git a/power_of_three/power_of_three.cpp b/power_of_three/power_of_three.cpp new file mode 100644 index 0000000..1852e62 --- /dev/null +++ b/power_of_three/power_of_three.cpp @@ -0,0 +1,6 @@ +class Solution { +public: + bool isPowerOfThree(int n) { + return (n > 0 && 1162261467 % n == 0); + } +}; \ No newline at end of file From 00de98997075e29feb24b5a480c554dd1fa2b225 Mon Sep 17 00:00:00 2001 From: zczou Date: Sun, 30 Oct 2016 23:17:44 +0800 Subject: [PATCH 56/73] 2 problems --- README.md | 2 + count_of_range_sum/count_of_range_sum.cpp | 28 ++++++++++++++ .../longest_increasing_path_in_a_matrix.cpp | 37 +++++++++++++++++++ 3 files changed, 67 insertions(+) create mode 100644 count_of_range_sum/count_of_range_sum.cpp create mode 100644 longest_increasing_path_in_a_matrix/longest_increasing_path_in_a_matrix.cpp diff --git a/README.md b/README.md index 57961a8..1fc27dd 100644 --- a/README.md +++ b/README.md @@ -234,6 +234,8 @@ Golang solution for leetcode. For each problem, there is a simple *_test.go to t #### [319. Bulb Switcher](https://github.com/hitzzc/go-leetcode/tree/master/bulb_switcher) #### [322. Coin Change](https://github.com/hitzzc/go-leetcode/tree/master/coin_change) #### [326. Power of Three](https://github.com/hitzzc/go-leetcode/tree/master/power_of_three) +#### [327. Count of Range Sum](https://github.com/hitzzc/go-leetcode/tree/master/count_of_range_sum) +#### [329. Longest Increasing Path in a Matrix](https://github.com/hitzzc/go-leetcode/tree/master/longest_increasing_path_in_a_matrix) diff --git a/count_of_range_sum/count_of_range_sum.cpp b/count_of_range_sum/count_of_range_sum.cpp new file mode 100644 index 0000000..da2fd9a --- /dev/null +++ b/count_of_range_sum/count_of_range_sum.cpp @@ -0,0 +1,28 @@ +class Solution { +public: + int countRangeSum(vector& nums, int lower, int upper) { + vector sums(nums.size()+1, 0); + for (int i = 0; i < nums.size(); ++i) { + sums[i+1] = sums[i] + nums[i]; + } + return count_when_merging_sort(sums, 0, sums.size(), lower, upper); + } + int count_when_merging_sort(vector& array, int start, int end, int lower, int upper) { + if (end-start <= 1) return 0; + int mid = start + (end-start)/2; + int j = mid, k = mid, t = mid; + int count = count_when_merging_sort(array, start, mid, lower, upper) + count_when_merging_sort(array, mid, end, lower, upper); + vector cache(end-start); + for (int i = start, r = 0; i < mid; ++i, ++r) { + while (k < end && array[k]-array[i] <= upper) ++k; + while (j < end && array[j]-array[i] < lower) ++j; + while (t < end && array[t] < array[i]) cache[r++] = array[t++]; + cache[r] = array[i]; + count += k - j; + } + for (int i = start; i < t; ++i) { + array[i] = cache[i-start]; + } + return count; + } +}; diff --git a/longest_increasing_path_in_a_matrix/longest_increasing_path_in_a_matrix.cpp b/longest_increasing_path_in_a_matrix/longest_increasing_path_in_a_matrix.cpp new file mode 100644 index 0000000..f99cacf --- /dev/null +++ b/longest_increasing_path_in_a_matrix/longest_increasing_path_in_a_matrix.cpp @@ -0,0 +1,37 @@ +class Solution { +public: + int longestIncreasingPath(vector>& matrix) { + int row = matrix.size(); + int col = row ? matrix[0].size() : 0; + vector> path(row, vector(col, 0)); + vector> visited(row, vector(col, 0)); + int ret = 0; + for (int i = 0; i < row; ++i) { + for (int j = 0; j < col; ++j) { + ret = max(ret, helper(matrix, path, row, col, i , j, visited)); + } + } + return ret; + } + + int helper(vector>& matrix, vector>& path, const int row, const int col, int r, int c, vector>& visited) { + if (path[r][c] > 0) return path[r][c]; + visited[r][c] = true; + int ret = 0; + if (r > 0 && !visited[r-1][c] && matrix[r][c] < matrix[r-1][c]) { + ret = max(ret, helper(matrix, path, row, col, r-1, c, visited)); + } + if (r < row-1 && !visited[r+1][c] && matrix[r][c] < matrix[r+1][c]) { + ret = max(ret, helper(matrix, path, row, col, r+1, c, visited)); + } + if (c > 0 && !visited[r][c-1] && matrix[r][c] < matrix[r][c-1]) { + ret = max(ret, helper(matrix, path, row, col, r, c-1, visited)); + } + if (c < col-1 && !visited[r][c+1] && matrix[r][c] < matrix[r][c+1]) { + ret = max(ret, helper(matrix, path, row, col, r, c+1, visited)); + } + visited[r][c] = false; + path[r][c] = ret+1; + return path[r][c]; + } +}; \ No newline at end of file From c0e298d6cc66f6de31a6b599f9849f7926dd6e9b Mon Sep 17 00:00:00 2001 From: zczou Date: Mon, 31 Oct 2016 22:56:47 +0800 Subject: [PATCH 57/73] 1 problem --- README.md | 1 + ...reorder_serialization_of_a_binary_tree.cpp | 21 +++++++++++++++++++ 2 files changed, 22 insertions(+) create mode 100644 verify_preorder_serialization_of_a_binary_tree/verify_preorder_serialization_of_a_binary_tree.cpp diff --git a/README.md b/README.md index 1fc27dd..6b28760 100644 --- a/README.md +++ b/README.md @@ -236,6 +236,7 @@ Golang solution for leetcode. For each problem, there is a simple *_test.go to t #### [326. Power of Three](https://github.com/hitzzc/go-leetcode/tree/master/power_of_three) #### [327. Count of Range Sum](https://github.com/hitzzc/go-leetcode/tree/master/count_of_range_sum) #### [329. Longest Increasing Path in a Matrix](https://github.com/hitzzc/go-leetcode/tree/master/longest_increasing_path_in_a_matrix) +#### [331. Verify Preorder Serialization of a Binary Tree](https://github.com/hitzzc/go-leetcode/tree/master/verify_preorder_serialization_of_a_binary_tree) diff --git a/verify_preorder_serialization_of_a_binary_tree/verify_preorder_serialization_of_a_binary_tree.cpp b/verify_preorder_serialization_of_a_binary_tree/verify_preorder_serialization_of_a_binary_tree.cpp new file mode 100644 index 0000000..08df9aa --- /dev/null +++ b/verify_preorder_serialization_of_a_binary_tree/verify_preorder_serialization_of_a_binary_tree.cpp @@ -0,0 +1,21 @@ +class Solution { +public: + bool isValidSerialization(string preorder) { + int idx = 0; + return helper(preorder, idx) ? idx == preorder.size() ? true : false : false; + } + + bool helper(string& preorder, int& idx) { + if (idx == preorder.size()) return false; + int start = idx; + while (idx < preorder.size() && preorder[idx] != ',') ++idx; + if (idx == preorder.size()) { + return preorder.substr(start) == "#" ? true : false; + } + ++idx; + if (preorder.substr(start, idx-start-1) == "#") + return true; + if (!helper(preorder, idx)) return false; + return helper(preorder, idx); + } +}; \ No newline at end of file From be9ad01ffc2acad06110312c3a80f973da345d82 Mon Sep 17 00:00:00 2001 From: zczou Date: Tue, 1 Nov 2016 18:24:39 +0800 Subject: [PATCH 58/73] 3 problems --- README.md | 3 +++ .../increasing_triplet_subsequence.cpp | 13 ++++++++++++ .../reconstruct_ltinerary.cpp | 21 +++++++++++++++++++ self_crossing/self_crossing.cpp | 15 +++++++++++++ 4 files changed, 52 insertions(+) create mode 100644 increasing_triplet_subsequence/increasing_triplet_subsequence.cpp create mode 100644 reconstruct_ltinerary/reconstruct_ltinerary.cpp create mode 100644 self_crossing/self_crossing.cpp diff --git a/README.md b/README.md index 6b28760..039e109 100644 --- a/README.md +++ b/README.md @@ -237,6 +237,9 @@ Golang solution for leetcode. For each problem, there is a simple *_test.go to t #### [327. Count of Range Sum](https://github.com/hitzzc/go-leetcode/tree/master/count_of_range_sum) #### [329. Longest Increasing Path in a Matrix](https://github.com/hitzzc/go-leetcode/tree/master/longest_increasing_path_in_a_matrix) #### [331. Verify Preorder Serialization of a Binary Tree](https://github.com/hitzzc/go-leetcode/tree/master/verify_preorder_serialization_of_a_binary_tree) +#### [332. Reconstruct Itinerary](https://github.com/hitzzc/go-leetcode/tree/master/reconstruct_ltinerary) +#### [334. Increasing Triplet Subsequence](https://github.com/hitzzc/go-leetcode/tree/master/increasing_triplet_subsequence) +#### [335. Self Crossing](https://github.com/hitzzc/go-leetcode/tree/master/self_crossing) diff --git a/increasing_triplet_subsequence/increasing_triplet_subsequence.cpp b/increasing_triplet_subsequence/increasing_triplet_subsequence.cpp new file mode 100644 index 0000000..4185e5d --- /dev/null +++ b/increasing_triplet_subsequence/increasing_triplet_subsequence.cpp @@ -0,0 +1,13 @@ +class Solution { +public: + bool increasingTriplet(vector& nums) { + if (nums.size() < 3) return false; + int first = nums[0], second = INT_MAX; + for (int i = 1; i < nums.size(); ++i) { + if (nums[i] > second) return true; + else if (nums[i] < first) first= nums[i]; + else if (nums[i] > first && nums[i] < second) second = nums[i]; + } + return false; + } +}; \ No newline at end of file diff --git a/reconstruct_ltinerary/reconstruct_ltinerary.cpp b/reconstruct_ltinerary/reconstruct_ltinerary.cpp new file mode 100644 index 0000000..3bfe90a --- /dev/null +++ b/reconstruct_ltinerary/reconstruct_ltinerary.cpp @@ -0,0 +1,21 @@ +class Solution { +public: + vector findItinerary(vector> tickets) { + unordered_map> graph; + for (auto& kv: tickets) { + graph[kv.first].insert(kv.second); + } + vector solution; + DFS(graph, solution, "JFK"); + return vector(solution.rbegin(), solution.rend()); + } + void DFS(unordered_map>& graph, vector& solution, string start) { + while (!graph[start].empty()) { + string city = *graph[start].begin(); + graph[start].erase(city); + (DFS(graph, solution, city)); + } + solution.push_back(start); + return; + } +}; \ No newline at end of file diff --git a/self_crossing/self_crossing.cpp b/self_crossing/self_crossing.cpp new file mode 100644 index 0000000..93cca29 --- /dev/null +++ b/self_crossing/self_crossing.cpp @@ -0,0 +1,15 @@ +class Solution { +public: + bool isSelfCrossing(vector& x) { + int m = x.size(); + for(int i=0; i=3 && x[i]>=x[i-2] && x[i-3]>=x[i-1]) + return true; + if(i>=4 && x[i-1]==x[i-3] && x[i]+x[i-4]>=x[i-2]) + return true; + if(i>=5 && x[i-3]>x[i-1] && x[i-2]>x[i-4] && x[i]+x[i-4]>=x[i-2] && x[i-1]+x[i-5]>=x[i-3]) + return true; + } + return false; + } +}; \ No newline at end of file From c3f470975b2f98b891403fc7a5bfe2f0507f22e1 Mon Sep 17 00:00:00 2001 From: zczou Date: Wed, 2 Nov 2016 12:55:06 +0800 Subject: [PATCH 59/73] palindrome_pairs --- README.md | 1 + palindrome_pairs/palindrome_pairs.cpp | 37 +++++++++++++++++++++++++++ 2 files changed, 38 insertions(+) create mode 100644 palindrome_pairs/palindrome_pairs.cpp diff --git a/README.md b/README.md index 039e109..781f166 100644 --- a/README.md +++ b/README.md @@ -240,6 +240,7 @@ Golang solution for leetcode. For each problem, there is a simple *_test.go to t #### [332. Reconstruct Itinerary](https://github.com/hitzzc/go-leetcode/tree/master/reconstruct_ltinerary) #### [334. Increasing Triplet Subsequence](https://github.com/hitzzc/go-leetcode/tree/master/increasing_triplet_subsequence) #### [335. Self Crossing](https://github.com/hitzzc/go-leetcode/tree/master/self_crossing) +#### [336. Palindrome Pairs](https://github.com/hitzzc/go-leetcode/tree/master/palindrome_pairs) diff --git a/palindrome_pairs/palindrome_pairs.cpp b/palindrome_pairs/palindrome_pairs.cpp new file mode 100644 index 0000000..9c7662b --- /dev/null +++ b/palindrome_pairs/palindrome_pairs.cpp @@ -0,0 +1,37 @@ +class Solution { +public: + vector> palindromePairs(vector& words) { + vector> results; + unordered_map mapping; + set index_set; + for (int i = 0; i < words.size(); ++i) { + mapping[words[i]] = i; + index_set.insert(words[i].size()); + } + for (int i = 0; i < words.size(); ++i) { + string word = words[i]; + int len = word.size(); + reverse(word.begin(), word.end()); + if (mapping.count(word) != 0 && mapping[word] != i) { + results.push_back(vector{i, mapping[word]}); + } + for (auto j = index_set.begin(); j != index_set.find(word.size()); ++j) { + int d = *j; + if (is_palindrome(word, 0, len - d - 1) && mapping.count(word.substr(len - d))) { + results.push_back({i, mapping[word.substr(len - d)]}); + } + if (is_palindrome(word, d, len - 1) && mapping.count(word.substr(0, d))) { + results.push_back({mapping[word.substr(0, d)], i}); + } + } + } + return results; + } + + bool is_palindrome(string& s, int i, int j) { + while (i < j) { + if (s[i++] != s[j--]) return false; + } + return true; + } +}; \ No newline at end of file From 0ddd7f305b7f182ca80b1d406f3e95e83e6e36f9 Mon Sep 17 00:00:00 2001 From: zczou Date: Wed, 2 Nov 2016 18:02:12 +0800 Subject: [PATCH 60/73] n --- README.md | 10 ++++ counting_bits/counting_bits.cpp | 11 ++++ counting_bits/t | Bin 0 -> 9684 bytes .../flatten_nested_list_iterator.cpp | 49 ++++++++++++++++++ house_robber_III/house_robber_III.cpp | 23 ++++++++ integer_break/integer_break.cpp | 14 +++++ .../intersection_of_two_arrays.cpp | 15 ++++++ .../intersection_of_two_arrays_II.cpp | 17 ++++++ power_of_four/power_of_four.cpp | 17 ++++++ reverse_string/reverse_string.cpp | 11 ++++ .../reverse_vowels_of_a_string.cpp | 21 ++++++++ .../top_k_frequent_elements.cpp | 22 ++++++++ 12 files changed, 210 insertions(+) create mode 100644 counting_bits/counting_bits.cpp create mode 100755 counting_bits/t create mode 100644 flatten_nested_list_iterator/flatten_nested_list_iterator.cpp create mode 100644 house_robber_III/house_robber_III.cpp create mode 100644 integer_break/integer_break.cpp create mode 100644 intersection_of_two_arrays/intersection_of_two_arrays.cpp create mode 100644 intersection_of_two_arrays_II/intersection_of_two_arrays_II.cpp create mode 100644 power_of_four/power_of_four.cpp create mode 100644 reverse_string/reverse_string.cpp create mode 100644 reverse_vowels_of_a_string/reverse_vowels_of_a_string.cpp create mode 100644 top_k_frequent_elements/top_k_frequent_elements.cpp diff --git a/README.md b/README.md index 781f166..ab17a8a 100644 --- a/README.md +++ b/README.md @@ -241,6 +241,16 @@ Golang solution for leetcode. For each problem, there is a simple *_test.go to t #### [334. Increasing Triplet Subsequence](https://github.com/hitzzc/go-leetcode/tree/master/increasing_triplet_subsequence) #### [335. Self Crossing](https://github.com/hitzzc/go-leetcode/tree/master/self_crossing) #### [336. Palindrome Pairs](https://github.com/hitzzc/go-leetcode/tree/master/palindrome_pairs) +#### [337. House Robber III](https://github.com/hitzzc/go-leetcode/tree/master/house_robber_III) +#### [338. Counting Bits](https://github.com/hitzzc/go-leetcode/tree/master/counting_bits) +#### [341. Flatten Nested List Iterator](https://github.com/hitzzc/go-leetcode/tree/master/flatten_nested_list_iterator) +#### [342. Power of Four](https://github.com/hitzzc/go-leetcode/tree/master/power_of_four) +#### [343. Integer Break](https://github.com/hitzzc/go-leetcode/tree/master/integer_break) +#### [344. Reverse String](https://github.com/hitzzc/go-leetcode/tree/master/reverse_string) +#### [345. Reverse Vowels of a String](https://github.com/hitzzc/go-leetcode/tree/master/reverse_vowels_of_a_string) +#### [347. Top K Frequent Elements](https://github.com/hitzzc/go-leetcode/tree/master/top_k_frequent_elements) +#### [349. Intersection of Two Arrays](https://github.com/hitzzc/go-leetcode/tree/master/intersection_of_two_arrays) +#### [350. Intersection of Two Arrays II](https://github.com/hitzzc/go-leetcode/tree/master/intersection_of_two_arrays_II) diff --git a/counting_bits/counting_bits.cpp b/counting_bits/counting_bits.cpp new file mode 100644 index 0000000..c8073de --- /dev/null +++ b/counting_bits/counting_bits.cpp @@ -0,0 +1,11 @@ +class Solution { +public: + vector countBits(int num) { + vector result(num+1); + result[0] = 0; + for (int i = 1; i <= num; ++i) { + result[i] = result[i&(i-1)] + 1; + } + return result; + } +}; \ No newline at end of file diff --git a/counting_bits/t b/counting_bits/t new file mode 100755 index 0000000000000000000000000000000000000000..462ab050ddeb434e2d8383094c15e207917551c3 GIT binary patch literal 9684 zcmeHNeQXp(6rXER3RZfciQwmfV5)@D4+dMLt9EeV#Sc*y5089T(8aDUb&)| zlpqPqrE-4}BgVi#h7e+iA*LEclakVZ6hsn@notup*MO$RL>hvgzc)MgwQUJC{<$xm zdGF1e_nS9wXRdoQcjeA+|14(ARmj+I0b|UKGW-BzhnWWwW2;b96wX`fb|`z4)?L(^ zPp*7*PK|I%F#zZ7N@sh17vWC>=aSSB8$&qkL22XM(4$7SqaAOu7?XkdxD1N)McMA8 z4CktxhmA;AIMZau8(e1LZI(UKdfK5#;$`C_Jnqv219}LZ?09D--s=*8bjo{%X2sX5 zXfD?2vE*VeBut0+Sd{w@($4SHnzf40cpzilXN=zV1`OBVuV z&!JF!9^{Ym{k+sEpAI=0a5CUzz{!A<0Vf0hEdw2@`HLC58^@n=cLQEr*y_vX%-*q* zXWkNkWLFQ}@_dfh1D5@<$@iuGve|Sbxf6=$ zGe|-_cJ8QhtmNW!vcpm_BV{<*oKX%(DP@@D!Amsfy<{C#%Q>SxnL!S!&%` ziU52x#i<`j+D+0m zlHMk1f}}4=x=2zH{HD&6w3ehZB)v$|Ns`)0It~f3ow&dXH^Gn9Q$<8VBg#9ZoI+WG zGK%6lgX$F&LBIe}{iKjAPPzvL&y{)b!bjgrYa!D+<9_)fPkIa9L+Lvly)PG|UMVD2 zFaXG53mO(ivlQB+q=5<#v@%!J?Q$0{E=s_X9=q^BOQWzXK2eQs?zCMvEugx97-_(9 z$*)TOz2rYj{=4Kek{8JDf5nn7U`VH{lL03KP6nI|I2mv<;AFtbfRh0y15O5<3^*BZ zGVniTVELNTR|#r)E$4fh+l(sCD>iBU5kq0SL+(UQYqe$!4d@M;Qt9tj7+H94G|F+! z9qtc$1Ab$O505#!aDEq zYPzAcHn){?YX}x9&+A;{?+^1XZ&=^ls~d1s23dlIYH~xbsDj06<-RrmN;Rr6{=`c=^i{tkb1)RD2 zy#65D!V3C)_&I^DMGPIkQt;CADciHj(8GqGRnqBHA)8!z9Ql-96p7ZR3zHE_oc13pj?L!F!I_Dz&O`+r93q(4_M|QdlCUzVJoQ4tf0cz-E z5=2LMx%y3;zQ!_U`oCt==}gS}v+z#Y^iOR16`MY3)Bm*TOAtAlGV#;BI^E~e86h1l z(|tHn#c&KJ?tAGTd<6=qmhPI72DTjKe*8QvXRqqP?!Y|Doc0p8?}&EZUd|PzZ3_nq z*8<*PFBVcDfZx@~wZ?XA-=6b}lYm}H#nQ5`K#K7`c6m;>IrevUqV{>* ub7wEqEwiT=>L_+|)=7SHW*hQ9G_&ow8y>CsTYZjAKKF<1tWR1jAke?WQ4 &getList() const; + * }; + */ +class NestedIterator { + vector v; + int index = 0; + void flatten(vector &nestedList) { + for (auto& item: nestedList) { + if (item.isInteger()) { + v.push_back(item.getInteger()); + }else { + flatten(item.getList()); + } + } + return; + } +public: + NestedIterator(vector &nestedList) { + flatten(nestedList); + } + + int next() { + return v[index++]; + } + + bool hasNext() { + return index < v.size(); + } +}; + +/** + * Your NestedIterator object will be instantiated and called as such: + * NestedIterator i(nestedList); + * while (i.hasNext()) cout << i.next(); + */ \ No newline at end of file diff --git a/house_robber_III/house_robber_III.cpp b/house_robber_III/house_robber_III.cpp new file mode 100644 index 0000000..ee6600f --- /dev/null +++ b/house_robber_III/house_robber_III.cpp @@ -0,0 +1,23 @@ +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode(int x) : val(x), left(NULL), right(NULL) {} +}; + +class Solution { + unordered_map records; +public: + int rob(TreeNode* root) { + if (root == NULL) return 0; + if (records.count(root) == 0) { + int left = rob(root->left); + int right = rob(root->right); + int without_left = 0, without_right = 0; + if (root->left) without_left = rob(root->left->left) + rob(root->left->right); + if (root->right) without_right = rob(root->right->left) + rob(root->right->right); + records[root] = max(root->val+without_left+without_right, left+right); + } + return records[root]; + } +}; \ No newline at end of file diff --git a/integer_break/integer_break.cpp b/integer_break/integer_break.cpp new file mode 100644 index 0000000..3378883 --- /dev/null +++ b/integer_break/integer_break.cpp @@ -0,0 +1,14 @@ +class Solution { +public: + int integerBreak(int n) { + if (n == 2) return 1; + if (n == 3) return 2; + int result = 1; + while (n > 4) { + result *= 3; + n -= 3; + } + result *= n; + return result; + } +}; \ No newline at end of file diff --git a/intersection_of_two_arrays/intersection_of_two_arrays.cpp b/intersection_of_two_arrays/intersection_of_two_arrays.cpp new file mode 100644 index 0000000..3ec2c25 --- /dev/null +++ b/intersection_of_two_arrays/intersection_of_two_arrays.cpp @@ -0,0 +1,15 @@ +class Solution { +public: + vector intersection(vector& nums1, vector& nums2) { + unordered_set s, visited; + for (auto& num: nums1) { + s.insert(num); + } + vector res; + for (auto& num: nums2) { + if (s.count(num) && visited.count(num) == 0) res.push_back(num); + visited.insert(num); + } + return res; + } +}; \ No newline at end of file diff --git a/intersection_of_two_arrays_II/intersection_of_two_arrays_II.cpp b/intersection_of_two_arrays_II/intersection_of_two_arrays_II.cpp new file mode 100644 index 0000000..e71e954 --- /dev/null +++ b/intersection_of_two_arrays_II/intersection_of_two_arrays_II.cpp @@ -0,0 +1,17 @@ +class Solution { +public: + vector intersect(vector& nums1, vector& nums2) { + unordered_map m; + for (auto& num: nums1) { + ++m[num]; + } + vector res; + for (auto& num: nums2) { + if (m[num] > 0) { + --m[num]; + res.push_back(num); + } + } + return res; + } +}; \ No newline at end of file diff --git a/power_of_four/power_of_four.cpp b/power_of_four/power_of_four.cpp new file mode 100644 index 0000000..87dd5f7 --- /dev/null +++ b/power_of_four/power_of_four.cpp @@ -0,0 +1,17 @@ +class Solution { +public: + bool isPowerOfFour(int num) { + static int mask = 0b01010101010101010101010101010101; + + //edge case + if (num<=0) return false; + + // there are multiple bits are 1 + if ((num & num-1) != 0) return false; + + // check which one bit is zero, if the place is 1 or 3 or 5 or 7 or 9..., + // then it is the power of 4 + if ((num & mask) != 0) return true; + return false; + } +}; \ No newline at end of file diff --git a/reverse_string/reverse_string.cpp b/reverse_string/reverse_string.cpp new file mode 100644 index 0000000..9aecb24 --- /dev/null +++ b/reverse_string/reverse_string.cpp @@ -0,0 +1,11 @@ +class Solution { +public: + string reverseString(string s) { + string ret(s.size(), '\0'); + for (int i = 0, j = s.size()-1; i <= j; ++i, --j) { + ret[i] = s[j]; + ret[j] = s[i]; + } + return ret; + } +}; \ No newline at end of file diff --git a/reverse_vowels_of_a_string/reverse_vowels_of_a_string.cpp b/reverse_vowels_of_a_string/reverse_vowels_of_a_string.cpp new file mode 100644 index 0000000..2f5c706 --- /dev/null +++ b/reverse_vowels_of_a_string/reverse_vowels_of_a_string.cpp @@ -0,0 +1,21 @@ +class Solution { +public: + string reverseVowels(string s) { + unordered_set vowels = {'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'}; + string ret(s.size(), '\0'); + for (int i = 0, j = s.size()-1; i <= j; ++i, --j) { + while (i < s.size()-1 && vowels.count(s[i]) == 0) { + ret[i] = s[i]; + ++i; + } + while (j >= 0 && vowels.count(s[j]) == 0) { + ret[j] = s[j]; + --j; + } + if (i > j) break; + ret[i] = s[j]; + ret[j] = s[i]; + } + return ret; + } +}; \ No newline at end of file diff --git a/top_k_frequent_elements/top_k_frequent_elements.cpp b/top_k_frequent_elements/top_k_frequent_elements.cpp new file mode 100644 index 0000000..d5f6452 --- /dev/null +++ b/top_k_frequent_elements/top_k_frequent_elements.cpp @@ -0,0 +1,22 @@ +class Solution { +public: + vector topKFrequent(vector& nums, int k) { + unordered_map mapping; + for (auto num: nums) { + ++mapping[num]; + } + vector> freq(nums.size()+1); + for (auto m: mapping) { + freq[m.second].push_back(m.first); + } + vector result; + for (int i = freq.size()-1; i >=0 && k > 0; --i) { + for (auto num: freq[i]) { + result.push_back(num); + --k; + if (k == 0) break; + } + } + return result; + } +}; \ No newline at end of file From 4ec491aa0b7cde01d779374c6075a784f996f5f8 Mon Sep 17 00:00:00 2001 From: zczou Date: Wed, 2 Nov 2016 21:43:42 +0800 Subject: [PATCH 61/73] russian_doll_envelopes --- README.md | 1 + .../russian_doll_envelopes.cpp | 24 +++++++++++++++++++ 2 files changed, 25 insertions(+) create mode 100644 russian_doll_envelopes/russian_doll_envelopes.cpp diff --git a/README.md b/README.md index ab17a8a..c27fdce 100644 --- a/README.md +++ b/README.md @@ -251,6 +251,7 @@ Golang solution for leetcode. For each problem, there is a simple *_test.go to t #### [347. Top K Frequent Elements](https://github.com/hitzzc/go-leetcode/tree/master/top_k_frequent_elements) #### [349. Intersection of Two Arrays](https://github.com/hitzzc/go-leetcode/tree/master/intersection_of_two_arrays) #### [350. Intersection of Two Arrays II](https://github.com/hitzzc/go-leetcode/tree/master/intersection_of_two_arrays_II) +#### [354. Russian Doll Envelopes](https://github.com/hitzzc/go-leetcode/tree/master/russian_doll_envelopes) diff --git a/russian_doll_envelopes/russian_doll_envelopes.cpp b/russian_doll_envelopes/russian_doll_envelopes.cpp new file mode 100644 index 0000000..26e01c3 --- /dev/null +++ b/russian_doll_envelopes/russian_doll_envelopes.cpp @@ -0,0 +1,24 @@ +class Solution { +public: + int maxEnvelopes(vector>& envelopes) { + vector dp; + sort(envelopes.begin(), envelopes.end(), [](const pair& a, const pair& b) { + if (a.first == b.first) return a.second > b.second; + return a.first < b.first; + }); + for (int i = 0; i < envelopes.size(); ++i) { + int left = 0, right = dp.size(); + while (left < right) { + int mid = left + (right-left)/2; + if (dp[mid] < envelopes[i].second) { + left = mid+1; + }else { + right = mid; + } + } + if (right >= dp.size()) dp.push_back(envelopes[i].second); + else dp[right] = envelopes[i].second; + } + return dp.size(); + } +}; \ No newline at end of file From ff8773e2d68fa39b0020d290b9bf91b5eadd41a4 Mon Sep 17 00:00:00 2001 From: zczou Date: Wed, 2 Nov 2016 23:16:19 +0800 Subject: [PATCH 62/73] 2 --- README.md | 2 ++ .../largest_divisible_subset.cpp | 32 +++++++++++++++++++ valid_perfect_square/valid_perfect_square.cpp | 16 ++++++++++ 3 files changed, 50 insertions(+) create mode 100644 largest_divisible_subset/largest_divisible_subset.cpp create mode 100644 valid_perfect_square/valid_perfect_square.cpp diff --git a/README.md b/README.md index c27fdce..085e15e 100644 --- a/README.md +++ b/README.md @@ -252,6 +252,8 @@ Golang solution for leetcode. For each problem, there is a simple *_test.go to t #### [349. Intersection of Two Arrays](https://github.com/hitzzc/go-leetcode/tree/master/intersection_of_two_arrays) #### [350. Intersection of Two Arrays II](https://github.com/hitzzc/go-leetcode/tree/master/intersection_of_two_arrays_II) #### [354. Russian Doll Envelopes](https://github.com/hitzzc/go-leetcode/tree/master/russian_doll_envelopes) +#### [367. Valid Perfect Square](https://github.com/hitzzc/go-leetcode/tree/master/valid_perfect_square) +#### [368. Largest Divisible Subset](https://github.com/hitzzc/go-leetcode/tree/master/largest_divisible_subset) diff --git a/largest_divisible_subset/largest_divisible_subset.cpp b/largest_divisible_subset/largest_divisible_subset.cpp new file mode 100644 index 0000000..df3a52b --- /dev/null +++ b/largest_divisible_subset/largest_divisible_subset.cpp @@ -0,0 +1,32 @@ +class Solution { +public: + vector largestDivisibleSubset(vector& nums) { + if (nums.size() == 0) return {}; + sort(nums.begin(), nums.end()); + vector dp(nums.size(), 1), pre(nums.size()); + for (int i = 0; i < pre.size(); ++i) { + pre[i] = i; + } + int max_v = 1, k = 0; + for (int i = 1; i < dp.size(); ++i) { + for (int j = i-1; j >= 0; --j) { + if (nums[i] % nums[j] != 0) continue; + if (dp[i] < dp[j]+1) { + pre[i] = j; + dp[i] = dp[j]+1; + } + if (dp[i] > max_v) { + max_v = dp[i]; + k = i; + } + } + } + vector result; + while (k != pre[k]) { + result.push_back(nums[k]); + k = pre[k]; + } + result.push_back(nums[k]); + return result; + } +}; \ No newline at end of file diff --git a/valid_perfect_square/valid_perfect_square.cpp b/valid_perfect_square/valid_perfect_square.cpp new file mode 100644 index 0000000..b227bc3 --- /dev/null +++ b/valid_perfect_square/valid_perfect_square.cpp @@ -0,0 +1,16 @@ +class Solution { +public: + bool isPerfectSquare(int num) { + long i = 1, j = num; + while (i <= j) { + long mid = i + (j-i)/2; + if (mid*mid == num) return true; + if (mid*mid < num) { + i = mid + 1; + }else { + j = mid - 1; + } + } + return false; + } +}; \ No newline at end of file From 455ef262b1a39060422791c4f209c7a009b69b37 Mon Sep 17 00:00:00 2001 From: zczou Date: Thu, 3 Nov 2016 10:56:31 +0800 Subject: [PATCH 63/73] 2 --- README.md | 2 ++ .../find_k_pairs_with_smallest_sums.cpp | 27 +++++++++++++++++++ sum_of_two_integers/sum_of_two_integers.cpp | 12 +++++++++ 3 files changed, 41 insertions(+) create mode 100644 find_k_pairs_with_smallest_sums/find_k_pairs_with_smallest_sums.cpp create mode 100644 sum_of_two_integers/sum_of_two_integers.cpp diff --git a/README.md b/README.md index 085e15e..b9229e4 100644 --- a/README.md +++ b/README.md @@ -254,6 +254,8 @@ Golang solution for leetcode. For each problem, there is a simple *_test.go to t #### [354. Russian Doll Envelopes](https://github.com/hitzzc/go-leetcode/tree/master/russian_doll_envelopes) #### [367. Valid Perfect Square](https://github.com/hitzzc/go-leetcode/tree/master/valid_perfect_square) #### [368. Largest Divisible Subset](https://github.com/hitzzc/go-leetcode/tree/master/largest_divisible_subset) +#### [371. Sum of Two Integers](https://github.com/hitzzc/go-leetcode/tree/master/sum_of_two_integers) +#### [373. Find K Pairs with Smallest Sums](https://github.com/hitzzc/go-leetcode/tree/master/find_k_pairs_with_smallest_sums) diff --git a/find_k_pairs_with_smallest_sums/find_k_pairs_with_smallest_sums.cpp b/find_k_pairs_with_smallest_sums/find_k_pairs_with_smallest_sums.cpp new file mode 100644 index 0000000..7fb91dd --- /dev/null +++ b/find_k_pairs_with_smallest_sums/find_k_pairs_with_smallest_sums.cpp @@ -0,0 +1,27 @@ +class Solution { +public: + vector> kSmallestPairs(vector& nums1, vector& nums2, int k) { + priority_queue, vector>, CMP> q; + vector> result; + for (int i = 0; i < min(k, (int)nums1.size()); ++i) { + for (int j = 0; j < min(k, (int)nums2.size()); ++j) { + auto node = make_pair(nums1[i], nums2[j]); + if (q.size() == k && node.first + node.second < q.top().first + q.top().second) { + q.pop(); + } + if (q.size() < k) q.push(node); + } + } + while (!q.empty()) { + result.push_back(q.top()); + q.pop(); + } + return result; + } + + struct CMP { + bool operator () (const pair& a, const pair& b) { + return a.first + a.second < b.first + b.second; + } + }; +}; \ No newline at end of file diff --git a/sum_of_two_integers/sum_of_two_integers.cpp b/sum_of_two_integers/sum_of_two_integers.cpp new file mode 100644 index 0000000..8eddf34 --- /dev/null +++ b/sum_of_two_integers/sum_of_two_integers.cpp @@ -0,0 +1,12 @@ +class Solution { +public: + int getSum(int a, int b) { + int carry = 0; + while (b != 0) { + carry = a & b; + a ^= b; + b = carry << 1; + } + return a; + } +}; \ No newline at end of file From a5fc56b2aa9ff3ee546c461ca95aa3456ebe32e2 Mon Sep 17 00:00:00 2001 From: zczou Date: Thu, 3 Nov 2016 13:24:14 +0800 Subject: [PATCH 64/73] 3 problems --- README.md | 3 +++ .../guess_number_higher_or_lower.cpp | 20 ++++++++++++++++++ .../guess_number_higher_or_lower_II.cpp | 16 ++++++++++++++ wiggle_subsequence/wiggle_subsequence.cpp | 21 +++++++++++++++++++ 4 files changed, 60 insertions(+) create mode 100644 guess_number_higher_or_lower/guess_number_higher_or_lower.cpp create mode 100644 guess_number_higher_or_lower_II/guess_number_higher_or_lower_II.cpp create mode 100644 wiggle_subsequence/wiggle_subsequence.cpp diff --git a/README.md b/README.md index b9229e4..fe752b5 100644 --- a/README.md +++ b/README.md @@ -256,6 +256,9 @@ Golang solution for leetcode. For each problem, there is a simple *_test.go to t #### [368. Largest Divisible Subset](https://github.com/hitzzc/go-leetcode/tree/master/largest_divisible_subset) #### [371. Sum of Two Integers](https://github.com/hitzzc/go-leetcode/tree/master/sum_of_two_integers) #### [373. Find K Pairs with Smallest Sums](https://github.com/hitzzc/go-leetcode/tree/master/find_k_pairs_with_smallest_sums) +#### [374. Guess Number Higher or Lower](https://github.com/hitzzc/go-leetcode/tree/master/guess_number_higher_or_lower) +#### [375. Guess Number Higher or Lower II](https://github.com/hitzzc/go-leetcode/tree/master/guess_number_higher_or_lower_II) +#### [376. Wiggle Subsequence](https://github.com/hitzzc/go-leetcode/tree/master/wiggle_subsequence) diff --git a/guess_number_higher_or_lower/guess_number_higher_or_lower.cpp b/guess_number_higher_or_lower/guess_number_higher_or_lower.cpp new file mode 100644 index 0000000..d18dfda --- /dev/null +++ b/guess_number_higher_or_lower/guess_number_higher_or_lower.cpp @@ -0,0 +1,20 @@ +// Forward declaration of guess API. +// @param num, your guess +// @return -1 if my number is lower, 1 if my number is higher, otherwise return 0 +int guess(int num); + +class Solution { +public: + int guessNumber(int n) { + int left = 1, right = n; + int mid; + while (left <= right) { + mid = left + (right-left)/2; + cout << mid << endl; + if (guess(mid) == 0) break; + else if (guess(mid) > 0) left = mid+1; + else right = mid-1; + } + return mid; + } +}; \ No newline at end of file diff --git a/guess_number_higher_or_lower_II/guess_number_higher_or_lower_II.cpp b/guess_number_higher_or_lower_II/guess_number_higher_or_lower_II.cpp new file mode 100644 index 0000000..8c6f623 --- /dev/null +++ b/guess_number_higher_or_lower_II/guess_number_higher_or_lower_II.cpp @@ -0,0 +1,16 @@ +class Solution { +public: + int getMoneyAmount(int n) { + vector> dp(n+1, vector(n+1, 0)); + for (int gap = 1; gap < n; ++gap) { + for (int low = 1; low <= n-gap; ++low) { + int high = low + gap; + dp[low][high] = INT_MAX; + for (int i = low; i < high; ++i) { + dp[low][high] = min(dp[low][high], i + max(dp[low][i-1], dp[i+1][high])); + } + } + } + return dp[1][n]; + } +}; \ No newline at end of file diff --git a/wiggle_subsequence/wiggle_subsequence.cpp b/wiggle_subsequence/wiggle_subsequence.cpp new file mode 100644 index 0000000..ead6588 --- /dev/null +++ b/wiggle_subsequence/wiggle_subsequence.cpp @@ -0,0 +1,21 @@ +class Solution { +public: + int wiggleMaxLength(vector& nums) { + if (nums.size() < 2) return nums.size(); + int inc_length = 1, dec_length = 1; + int pre_inc_v = nums[0], pre_dec_v = nums[0]; + for (int i = 1; i < nums.size(); ++i) { + if (nums[i] < pre_inc_v && dec_length <= inc_length) { + dec_length = inc_length + 1; + pre_dec_v = nums[i]; + } + if (nums[i] > pre_dec_v && inc_length <= dec_length) { + inc_length = dec_length + 1; + pre_inc_v = nums[i]; + } + if (nums[i] > pre_inc_v) pre_inc_v = nums[i]; + if (nums[i] < pre_dec_v) pre_dec_v = nums[i]; + } + return max(inc_length, dec_length); + } +}; \ No newline at end of file From ffda9a663ae4cdb1c2dc1e9dc75b784c7ce60c40 Mon Sep 17 00:00:00 2001 From: zczou Date: Thu, 3 Nov 2016 14:30:08 +0800 Subject: [PATCH 65/73] 2 --- README.md | 2 ++ combination_sum_IV/combination_sum_IV.cpp | 15 +++++++++++++++ .../kth_smallest_element_in_a_sorted_matrix.cpp | 16 ++++++++++++++++ 3 files changed, 33 insertions(+) create mode 100644 combination_sum_IV/combination_sum_IV.cpp create mode 100644 kth_smallest_element_in_a_sorted_matrix/kth_smallest_element_in_a_sorted_matrix.cpp diff --git a/README.md b/README.md index fe752b5..baaacf0 100644 --- a/README.md +++ b/README.md @@ -259,6 +259,8 @@ Golang solution for leetcode. For each problem, there is a simple *_test.go to t #### [374. Guess Number Higher or Lower](https://github.com/hitzzc/go-leetcode/tree/master/guess_number_higher_or_lower) #### [375. Guess Number Higher or Lower II](https://github.com/hitzzc/go-leetcode/tree/master/guess_number_higher_or_lower_II) #### [376. Wiggle Subsequence](https://github.com/hitzzc/go-leetcode/tree/master/wiggle_subsequence) +#### [377. Combination Sum IV](https://github.com/hitzzc/go-leetcode/tree/master/combination_sum_IV) +#### [378. Kth Smallest Element in a Sorted Matrix](https://github.com/hitzzc/go-leetcode/tree/master/kth_smallest_element_in_a_sorted_matrix) diff --git a/combination_sum_IV/combination_sum_IV.cpp b/combination_sum_IV/combination_sum_IV.cpp new file mode 100644 index 0000000..1394d31 --- /dev/null +++ b/combination_sum_IV/combination_sum_IV.cpp @@ -0,0 +1,15 @@ +class Solution { +public: + int combinationSum4(vector& nums, int target) { + vector dp(target+1, 0); + dp[0] = 1; + for (int i = 1; i <= target; ++i) { + for (auto& num: nums) { + if (num <= i) { + dp[i] += dp[i-num]; + } + } + } + return dp[target]; + } +}; \ No newline at end of file diff --git a/kth_smallest_element_in_a_sorted_matrix/kth_smallest_element_in_a_sorted_matrix.cpp b/kth_smallest_element_in_a_sorted_matrix/kth_smallest_element_in_a_sorted_matrix.cpp new file mode 100644 index 0000000..b17e876 --- /dev/null +++ b/kth_smallest_element_in_a_sorted_matrix/kth_smallest_element_in_a_sorted_matrix.cpp @@ -0,0 +1,16 @@ +class Solution { +public: + int kthSmallest(vector>& matrix, int k) { + int left = matrix[0][0], right = matrix.back().back(); + while (left < right) { + int mid = left + (right - left)/2; + int cnt = 0; + for (auto& vec: matrix) { + cnt += upper_bound(vec.begin(), vec.end(), mid) - vec.begin(); + } + if (cnt < k) left = mid + 1; + else right = mid; + } + return left; + } +}; \ No newline at end of file From 898e46819bdaf21ffe833bc375705e529623455a Mon Sep 17 00:00:00 2001 From: zczou Date: Thu, 3 Nov 2016 15:02:48 +0800 Subject: [PATCH 66/73] 3 --- README.md | 3 ++ .../lexicographical_numbers.cpp | 21 +++++++++++++ ransom_note/ransom_note.cpp | 14 +++++++++ shuffle_an_array/shuffle_an_array.cpp | 30 +++++++++++++++++++ 4 files changed, 68 insertions(+) create mode 100644 lexicographical_numbers/lexicographical_numbers.cpp create mode 100644 ransom_note/ransom_note.cpp create mode 100644 shuffle_an_array/shuffle_an_array.cpp diff --git a/README.md b/README.md index baaacf0..c7c87e7 100644 --- a/README.md +++ b/README.md @@ -261,6 +261,9 @@ Golang solution for leetcode. For each problem, there is a simple *_test.go to t #### [376. Wiggle Subsequence](https://github.com/hitzzc/go-leetcode/tree/master/wiggle_subsequence) #### [377. Combination Sum IV](https://github.com/hitzzc/go-leetcode/tree/master/combination_sum_IV) #### [378. Kth Smallest Element in a Sorted Matrix](https://github.com/hitzzc/go-leetcode/tree/master/kth_smallest_element_in_a_sorted_matrix) +#### [383. Ransom Note](https://github.com/hitzzc/go-leetcode/tree/master/ransom_note) +#### [384. Shuffle an Array](https://github.com/hitzzc/go-leetcode/tree/master/shuffle_an_array) +#### [386. Lexicographical Numbers](https://github.com/hitzzc/go-leetcode/tree/master/lexicographical_numbers) diff --git a/lexicographical_numbers/lexicographical_numbers.cpp b/lexicographical_numbers/lexicographical_numbers.cpp new file mode 100644 index 0000000..91d093a --- /dev/null +++ b/lexicographical_numbers/lexicographical_numbers.cpp @@ -0,0 +1,21 @@ +class Solution { +public: + vector lexicalOrder(int n) { + vector result; + for (int i = 1; i <= n && i <= 9; ++i) { + result.push_back(i); + helper(i, n, result); + } + return result; + } + + void helper(int num, int n, vector& result) { + for (int i = 0; i <= 9; ++i) { + int tmp = num*10 + i; + if (tmp > n) break; + result.push_back(tmp); + helper(tmp, n, result); + } + return; + } +}; \ No newline at end of file diff --git a/ransom_note/ransom_note.cpp b/ransom_note/ransom_note.cpp new file mode 100644 index 0000000..31dc1dd --- /dev/null +++ b/ransom_note/ransom_note.cpp @@ -0,0 +1,14 @@ +class Solution { +public: + bool canConstruct(string ransomNote, string magazine) { + vector count(26, 0); + for (auto& ch: magazine) { + ++count[ch-'a']; + } + for (auto& ch: ransomNote) { + if (count[ch-'a'] <= 0) return false; + --count[ch-'a']; + } + return true; + } +}; \ No newline at end of file diff --git a/shuffle_an_array/shuffle_an_array.cpp b/shuffle_an_array/shuffle_an_array.cpp new file mode 100644 index 0000000..3a201b5 --- /dev/null +++ b/shuffle_an_array/shuffle_an_array.cpp @@ -0,0 +1,30 @@ +class Solution { +public: + Solution(vector nums): nums(nums), current(nums) { + srand(time(NULL)); + } + + /** Resets the array to its original configuration and return it. */ + vector reset() { + return current = nums; + } + + /** Returns a random shuffling of the array. */ + vector shuffle() { + int i = current.size(); + while (--i > 0) { + int j = rand() % (i+1); + swap(current[i], current[j]); + } + return current; + } +private: + vector nums, current; +}; + +/** + * Your Solution object will be instantiated and called as such: + * Solution obj = new Solution(nums); + * vector param_1 = obj.reset(); + * vector param_2 = obj.shuffle(); + */ \ No newline at end of file From 3a548773d30c42336de8dabec3fd8ddd1abdd090 Mon Sep 17 00:00:00 2001 From: zczou Date: Thu, 3 Nov 2016 15:43:26 +0800 Subject: [PATCH 67/73] 2 --- README.md | 3 +++ .../first_unique_character_in_a_string.cpp | 13 ++++++++++ .../longest_absolute_file_path.cpp | 24 +++++++++++++++++++ 3 files changed, 40 insertions(+) create mode 100644 first_unique_character_in_a_string/first_unique_character_in_a_string.cpp create mode 100644 longest_absolute_file_path/longest_absolute_file_path.cpp diff --git a/README.md b/README.md index c7c87e7..0856c26 100644 --- a/README.md +++ b/README.md @@ -264,6 +264,9 @@ Golang solution for leetcode. For each problem, there is a simple *_test.go to t #### [383. Ransom Note](https://github.com/hitzzc/go-leetcode/tree/master/ransom_note) #### [384. Shuffle an Array](https://github.com/hitzzc/go-leetcode/tree/master/shuffle_an_array) #### [386. Lexicographical Numbers](https://github.com/hitzzc/go-leetcode/tree/master/lexicographical_numbers) +#### [387. First Unique Character in a String](https://github.com/hitzzc/go-leetcode/tree/master/first_unique_character_in_a_string) +#### [388. Longest Absolute File Path](https://github.com/hitzzc/go-leetcode/tree/master/longest_absolute_file_path) + diff --git a/first_unique_character_in_a_string/first_unique_character_in_a_string.cpp b/first_unique_character_in_a_string/first_unique_character_in_a_string.cpp new file mode 100644 index 0000000..32cdf3a --- /dev/null +++ b/first_unique_character_in_a_string/first_unique_character_in_a_string.cpp @@ -0,0 +1,13 @@ +class Solution { +public: + int firstUniqChar(string s) { + unordered_map m; + for (auto& ch: s) { + ++m[ch]; + } + for (int i = 0; i < s.size(); ++i) { + if (m[s[i]] == 1) return i; + } + return -1; + } +}; \ No newline at end of file diff --git a/longest_absolute_file_path/longest_absolute_file_path.cpp b/longest_absolute_file_path/longest_absolute_file_path.cpp new file mode 100644 index 0000000..5cd63e6 --- /dev/null +++ b/longest_absolute_file_path/longest_absolute_file_path.cpp @@ -0,0 +1,24 @@ +class Solution { +public: + int lengthLongestPath(string input) { + unordered_map depth; + int level = 0, res = 0; + for (int i = 0; i < input.size(); ++i) { + int start = i; + while (i < input.size() && input[i] != '\n' && input[i] != '\t') ++i; + if (i == input.size() || input[i] == '\n') { + string name = input.substr(start, i-start); + if (name.find('.') != string::npos) { + res = max(res, depth[level] + (int)name.size()); + }else { + ++level; + depth[level] = depth[level-1] + (int)name.size() + 1; + } + level = 0; + }else { + ++level; + } + } + return res; + } +}; \ No newline at end of file From 0ba6c17d60e9ca2426efef2b162a89a26addd572 Mon Sep 17 00:00:00 2001 From: zczou Date: Thu, 3 Nov 2016 17:54:58 +0800 Subject: [PATCH 68/73] n --- README.md | 7 +++++ decode_string/decode_string.cpp | 28 +++++++++++++++++++ elimination_game/elimination_game.cpp | 6 ++++ find_the_difference/find_the_difference.cpp | 18 ++++++++++++ is_subsequence/is_subsequence.cpp | 11 ++++++++ ...g_with_at_least_k_repeating_characters.cpp | 23 +++++++++++++++ nth_digit/nth_digit.cpp | 15 ++++++++++ rotate_function/rotate_function.cpp | 19 +++++++++++++ 8 files changed, 127 insertions(+) create mode 100644 decode_string/decode_string.cpp create mode 100644 elimination_game/elimination_game.cpp create mode 100644 find_the_difference/find_the_difference.cpp create mode 100644 is_subsequence/is_subsequence.cpp create mode 100644 longest_substring_with_at_least_k_repeating_characters/longest_substring_with_at_least_k_repeating_characters.cpp create mode 100644 nth_digit/nth_digit.cpp create mode 100644 rotate_function/rotate_function.cpp diff --git a/README.md b/README.md index 0856c26..bedc0ae 100644 --- a/README.md +++ b/README.md @@ -266,6 +266,13 @@ Golang solution for leetcode. For each problem, there is a simple *_test.go to t #### [386. Lexicographical Numbers](https://github.com/hitzzc/go-leetcode/tree/master/lexicographical_numbers) #### [387. First Unique Character in a String](https://github.com/hitzzc/go-leetcode/tree/master/first_unique_character_in_a_string) #### [388. Longest Absolute File Path](https://github.com/hitzzc/go-leetcode/tree/master/longest_absolute_file_path) +#### [389. Find the Difference](https://github.com/hitzzc/go-leetcode/tree/master/find_the_difference) +#### [390. Elimination Game](https://github.com/hitzzc/go-leetcode/tree/master/elimination_game) +#### [391. Is Subsequence](https://github.com/hitzzc/go-leetcode/tree/master/is_subsequence) +#### [394. Decode String](https://github.com/hitzzc/go-leetcode/tree/master/decode_string) +#### [395. Longest Substring with At Least K Repeating Characters](https://github.com/hitzzc/go-leetcode/tree/master/longest_substring_with_at_least_k_repeating_characters) +#### [396. Rotate Function](https://github.com/hitzzc/go-leetcode/tree/master/rotate_function) +#### [400. Nth Digit](https://github.com/hitzzc/go-leetcode/tree/master/nth_digit) diff --git a/decode_string/decode_string.cpp b/decode_string/decode_string.cpp new file mode 100644 index 0000000..5980e7f --- /dev/null +++ b/decode_string/decode_string.cpp @@ -0,0 +1,28 @@ +class Solution { +public: + string decodeString(string s) { + int i = 0; + return decode(s, i); + } + + string decode(string& s, int& idx) { + string ret; + while (idx < s.size() && s[idx] != ']') { + if (s[idx] < '0' || s[idx] > '9') { + ret += s[idx++]; + } else { + int num = 0; + while (s[idx] != '[') { + num = 10*num + s[idx++] - '0'; + } + ++idx; + string tmp = decode(s, idx); + while (num-- > 0) { + ret += tmp; + } + ++idx; + } + } + return ret; + } +}; \ No newline at end of file diff --git a/elimination_game/elimination_game.cpp b/elimination_game/elimination_game.cpp new file mode 100644 index 0000000..cb357d8 --- /dev/null +++ b/elimination_game/elimination_game.cpp @@ -0,0 +1,6 @@ +class Solution { +public: + int lastRemaining(int n) { + return n == 1 ? 1 : 2*(n/2 + 1 - lastRemaining(n/2)); + } +}; \ No newline at end of file diff --git a/find_the_difference/find_the_difference.cpp b/find_the_difference/find_the_difference.cpp new file mode 100644 index 0000000..6ad08af --- /dev/null +++ b/find_the_difference/find_the_difference.cpp @@ -0,0 +1,18 @@ +class Solution { +public: + char findTheDifference(string s, string t) { + vector vec(26, 0); + for (auto& c: s) { + ++vec[c-'a']; + } + char ret; + for (auto& c: t) { + if (vec[c-'a'] == 0) { + ret = c; + break; + } + --vec[c-'a']; + } + return ret; + } +}; \ No newline at end of file diff --git a/is_subsequence/is_subsequence.cpp b/is_subsequence/is_subsequence.cpp new file mode 100644 index 0000000..ac29f57 --- /dev/null +++ b/is_subsequence/is_subsequence.cpp @@ -0,0 +1,11 @@ +class Solution { +public: + bool isSubsequence(string s, string t) { + if (s.size() == 0) return true; + int ps = 0, pt = 0; + for (; pt < t.size() && ps < t.size(); ++pt) { + if (s[ps] == t[pt]) ++ps; + } + return ps == s.size(); + } +}; \ No newline at end of file diff --git a/longest_substring_with_at_least_k_repeating_characters/longest_substring_with_at_least_k_repeating_characters.cpp b/longest_substring_with_at_least_k_repeating_characters/longest_substring_with_at_least_k_repeating_characters.cpp new file mode 100644 index 0000000..ea40f04 --- /dev/null +++ b/longest_substring_with_at_least_k_repeating_characters/longest_substring_with_at_least_k_repeating_characters.cpp @@ -0,0 +1,23 @@ +class Solution { +public: + int longestSubstring(string s, int k) { + int ret = 0; + int i = 0; + while (i+k < s.size()) { + int mask = 0, i_max = i; + vector cnt(26, 0); + for (int j = i; j < s.size(); ++j) { + int idx = s[j] - 'a'; + ++cnt[idx]; + if (cnt[idx] < k) mask |= (1 << idx); + else mask &= ~(1 << idx); + if (mask == 0) { + ret = max(ret, j-i+1); + i_max = j; + } + } + i = i_max + 1; + } + return ret; + } +}; \ No newline at end of file diff --git a/nth_digit/nth_digit.cpp b/nth_digit/nth_digit.cpp new file mode 100644 index 0000000..5fb1c72 --- /dev/null +++ b/nth_digit/nth_digit.cpp @@ -0,0 +1,15 @@ +class Solution { +public: + int findNthDigit(int n) { + long len = 1; + long count = 9; + long start = 1; + while (n > len*count) { + n -= len*count; + start += count; + ++len; + count *= 10; + } + return to_string(start + (n-1)/len)[(n-1)%len] - '0'; + } +}; \ No newline at end of file diff --git a/rotate_function/rotate_function.cpp b/rotate_function/rotate_function.cpp new file mode 100644 index 0000000..204f5e1 --- /dev/null +++ b/rotate_function/rotate_function.cpp @@ -0,0 +1,19 @@ +class Solution { +public: + int maxRotateFunction(vector& A) { + if (A.size() == 0) return 0; + int sum = 0; + int pre = 0; + for (int i = 0; i < A.size(); ++i) { + sum += A[i]; + pre += i * A[i]; + } + int ret = pre; + int len = A.size(); + for (int i = 0; i < len-1; ++i) { + pre = pre - sum + len*A[i]; + ret = max(ret, pre); + } + return ret; + } +}; \ No newline at end of file From 0f3275134adb13641a2d3fbf7ce6c1199576ec7c Mon Sep 17 00:00:00 2001 From: zczou Date: Fri, 4 Nov 2016 13:41:26 +0800 Subject: [PATCH 69/73] regular_expression_matching --- README.md | 1 + .../regular_expression_matching.cpp | 26 +++++++++++++++++++ 2 files changed, 27 insertions(+) create mode 100644 regular_expression_matching/regular_expression_matching.cpp diff --git a/README.md b/README.md index bedc0ae..45f1b35 100644 --- a/README.md +++ b/README.md @@ -11,6 +11,7 @@ Golang solution for leetcode. For each problem, there is a simple *_test.go to t #### [7. reverse integer](https://github.com/hitzzc/go-leetcode/tree/master/reverse_integer) #### [8. string to integer](https://github.com/hitzzc/go-leetcode/tree/master/string_to_integer) #### [9. palindrome number](https://github.com/hitzzc/go-leetcode/tree/master/palindrome_number) +#### [10. Regular Expression Matching](https://github.com/hitzzc/go-leetcode/tree/master/regular_expression_matching) #### [11. container with most water](https://github.com/hitzzc/go-leetcode/tree/master/container_with_most_water) #### [12. integer to roman](https://github.com/hitzzc/go-leetcode/tree/master/integer_to_roman) #### [13. roman to integer](https://github.com/hitzzc/go-leetcode/tree/master/roman_to_integer) diff --git a/regular_expression_matching/regular_expression_matching.cpp b/regular_expression_matching/regular_expression_matching.cpp new file mode 100644 index 0000000..fea5b40 --- /dev/null +++ b/regular_expression_matching/regular_expression_matching.cpp @@ -0,0 +1,26 @@ +class Solution { +public: + bool isMatch(string s, string p) { + return isMatch(s, p, s.size(), p.size()); + } + bool isMatch(string& s, string& p, int i, int j) { + if (i == 0 && j == 0) return true; + if (i != 0 && j == 0) return false; + if (i == 0 && j != 0) { + if (p[j-1] == '*') { + return isMatch(s, p, i, j-2); + } + return false; + } + if (s[i-1] == p[j-1] || p[j-1] == '.') { + return isMatch(s, p, i-1, j-1); + } else if (p[j-1] == '*') { + if (isMatch(s, p, i, j-2)) return true; + if (s[i-1] == p[j-2] || p[j-2] == '.') { + return isMatch(s, p, i-1, j); + } + return false; + } + return false; + } +}; \ No newline at end of file From 0e122459ed334fbdb8cf716bfc436be0e557a72e Mon Sep 17 00:00:00 2001 From: zczou Date: Mon, 5 Jun 2017 02:11:10 +0800 Subject: [PATCH 70/73] update --- .../find_minimum_in_rotated_sorted_array_II.go | 9 ++------- 1 file changed, 2 insertions(+), 7 deletions(-) diff --git a/find_minimum_in_rotated_sorted_array_II/find_minimum_in_rotated_sorted_array_II.go b/find_minimum_in_rotated_sorted_array_II/find_minimum_in_rotated_sorted_array_II.go index cb3d9e4..6a8ed86 100644 --- a/find_minimum_in_rotated_sorted_array_II/find_minimum_in_rotated_sorted_array_II.go +++ b/find_minimum_in_rotated_sorted_array_II/find_minimum_in_rotated_sorted_array_II.go @@ -12,17 +12,12 @@ func helper(nums []int, left, right int) int { return nums[left] } mid := left + (right-left)/2 - if mid == left { - return helper(nums, left+1, right) - } if nums[left] == nums[mid] && nums[mid] == nums[right] { - for ; left < right && nums[left] == nums[left+1]; left++ { - } - for ; left < right && nums[right] == nums[right-1]; right-- { + for ; left < right && nums[left] == nums[right]; left++ { } return helper(nums, left, right) } - if nums[left] <= nums[mid] && nums[mid] > nums[right] { + if nums[left] <= nums[mid] { return helper(nums, mid+1, right) } return helper(nums, left, mid) From 8547e55f43fbdc77fb327ebac51ad612f99bee13 Mon Sep 17 00:00:00 2001 From: Sandy Date: Mon, 10 Dec 2018 16:48:38 +0800 Subject: [PATCH 71/73] Update remove_element.go --- remove_element/remove_element.go | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/remove_element/remove_element.go b/remove_element/remove_element.go index 1765abf..408ac94 100644 --- a/remove_element/remove_element.go +++ b/remove_element/remove_element.go @@ -1,13 +1,13 @@ package remove_element func removeElement(nums []int, val int) int { - start := 0 - for i := 0; i < len(nums); i++ { - if nums[i] == val { - continue - } - nums[start] = nums[i] - start++ - } - return start + l := 0 + for _, v := range nums { + if v != val { + nums[l] = v + l++ + } + } + + return l } From 230388b0835578bd555c0f9e9d6c0532e60347d0 Mon Sep 17 00:00:00 2001 From: Sandy Date: Fri, 14 Dec 2018 11:38:36 +0800 Subject: [PATCH 72/73] Update valid_parentheses.go --- valid_parentheses/valid_parentheses.go | 67 +++++++++----------------- 1 file changed, 22 insertions(+), 45 deletions(-) diff --git a/valid_parentheses/valid_parentheses.go b/valid_parentheses/valid_parentheses.go index 3de3451..54151ed 100644 --- a/valid_parentheses/valid_parentheses.go +++ b/valid_parentheses/valid_parentheses.go @@ -1,49 +1,26 @@ package valid_parentheses func isValid(s string) bool { - if len(s)%2 != 0 { - return false - } - left := map[byte]struct{}{ - '(': struct{}{}, - '[': struct{}{}, - '{': struct{}{}, - } - right := map[byte]struct{}{ - ')': struct{}{}, - ']': struct{}{}, - '}': struct{}{}, - } - bytes := []byte(s) - stack := []byte{} - for i := range bytes { - if _, ok := left[bytes[i]]; ok { - stack = append(stack, bytes[i]) - } else if _, ok = right[bytes[i]]; ok { - if len(stack) == 0 { - return false - } - switch stack[len(stack)-1] { - case '(': - if bytes[i] != ')' { - return false - } - case '[': - if bytes[i] != ']' { - return false - } - case '{': - if bytes[i] != '}' { - return false - } - } - stack = stack[:len(stack)-1] - } else { - return false - } - } - if len(stack) == 0 { - return true - } - return false + m := map[rune]rune{ + '(': ')', + '[': ']', + '{': '}', + } + stack := make([]rune, len(s)) + top := 0 + for _, c := range s { + switch c { + case '(', '[', '{': + stack[top] = m[c] + top++ + case ')', ']', '}': + if top > 0 && stack[top-1] == c { + top-- + } else { + return false + } + } + } + + return top == 0 } From d5849f387720ddee27e7daefd049e9a2b5977b9c Mon Sep 17 00:00:00 2001 From: "Jithin.S" Date: Mon, 9 Dec 2019 23:36:56 +0530 Subject: [PATCH 73/73] changed for loop condition --- plus_one/plus_one.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/plus_one/plus_one.go b/plus_one/plus_one.go index ab91ce3..b9711b7 100644 --- a/plus_one/plus_one.go +++ b/plus_one/plus_one.go @@ -2,7 +2,7 @@ package plus_one func plusOne(digits []int) []int { carry := 1 - for i := len(digits); i >= 0; i++ { + for i := len(digits)-1; i >= 0; i-- { sum := carry + digits[i] if sum < 10 { digits[i] = sum