diff --git a/.gitignore b/.gitignore index 015e28a..897a0ef 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,5 @@ *.DS_Store *.vscode a.out -*__pycache__ \ No newline at end of file +*__pycache__ +test.c diff --git a/1.cpp b/1.cpp deleted file mode 100644 index 6c82d5a..0000000 --- a/1.cpp +++ /dev/null @@ -1,66 +0,0 @@ -// you can use includes, for example: -// #include - -// you can write to stdout for debugging purposes, e.g. -// cout << "this is a debug message" << endl; -#include -int solution(string &A, string &B) { - // write your code in C++14 (g++ 6.2.0) - // 計算 有多少回合,每回合 15 分鐘 ,分別是 - // HH:00 HH:15 HH:30 HH:45 - int count = 0; - int ehour = 10*(A[0] - '0') + (A[1]-'0'); - int lhour = 10*(B[0] - '0') + (B[1]-'0'); - int hours = (lhour - ehour+24) %24; - int emin = 10*(A[3] - '0') + (A[4]-'0'); - int lmin = 10*(B[3] - '0') + (B[4]-'0'); - int mins = lmin - emin; - if(hours==0 && mins ==0) return 0; - - // avoid 00:01 -> 01:01 - if(mins==0 && emin!=0 && emin!= 15 && emin!= 30 && emin!= 45){ - return hours*4-1; - } - // 未滿一小時 - if(hours == 0){ - if(mins< 0) return 0; - // 不是整點開始 - if( emin!=0 && emin!= 15 && emin!= 30 && emin!= 45){ - // 前進到最近的整點 - int e = emin + 15 - (emin%15); - int period = (lmin - e ) /15; - return period; - } - else{ - // 整點開始 - int period = (lmin - emin ) /15; - return period; - - } - } - else{ - count = hours *4; - // 處理分鐘 - if(mins< 0) return count; - // 不是整點開始 - if( emin!=0 && emin!= 15 && emin!= 30 && emin!= 45){ - // 前進到最近的整點 - int e = emin + 15 - (emin%15); - int period = count; - cout<< abs(lmin - e ) /15< - -// you can write to stdout for debugging purposes, e.g. -// cout << "this is a debug message" << endl; - -int solution(vector &A) -{ - // write your code in C++14 (g++ 6.2.0) - - // int n = A.size(); - - // 10 -10 -1 -1 10 - // 10 0 -1 -2 10 - // 10 0 -1 - // revisit - // 10 0 -1 -1 10 - // 10 10 9 8 18 - - // -1 -1 -1 1 1 1 1 - // 0 0 0 1 2 3 4 - // - - // 5 -2 -3 1 - // 5 3 0 1 - - // 假設陣列總和非負,代表解必定存在 - // 移動多少次收支可以讓公司不會負債 - // 確保當前總和為大於等於0 - // 一開始遇到負數肯定負債 - // 每次遇到當前總和為負數時,將先前最小負數位置補零,移動次數加一,並重新拜訪 - - // O(n^2 ) maybe timeout - - // 確保當前總和為大於等於0 - if (A.size() == 1) - return 0; - int count = 0; - vector arr = A; - int total = 0; - for (int a : arr) - { - total += a; - if (total < 0) - break; - } - if (total == 0) - return 0; - - while (total < 0) - { - int curmin = 0; - int idxmin = -1; - int sum = 0; - for (int i = 0; i < (int)arr.size(); ++i) - { - if (arr[i] < curmin) - { - curmin = arr[i]; - idxmin = i; - } - sum += arr[i]; - if (sum < 0) - { - sum -= arr[i]; - arr[idxmin] = 0; - count++; - break; - } - } - total = 0; - for (int a : arr) - { - total += a; - if (total < 0) - break; - } - } - return count; -} diff --git a/3.cpp b/3.cpp deleted file mode 100644 index 7a6ed71..0000000 --- a/3.cpp +++ /dev/null @@ -1,52 +0,0 @@ -// you can use includes, for example: -// #include - -// you can write to stdout for debugging purposes, e.g. -// cout << "this is a debug message" << endl; -#include -#include -int solution(int N, vector &A, vector &B) { - // write your code in C++14 (g++ 6.2.0) - // 圖中最大總和路徑 - // M = 5 - // (2,1) (2,3) (1,4) (2,4) - - - vector> points; - - vector> edges(N, vector(N,0)); - for(int i=0;i<(int)A.size();++i){ - edges[A[i] -1][B[i]-1]++; - edges[B[i]-1][A[i]-1 ]++; - } - - vector> vec; - for(int i=0;i<(int)edges.size() ; ++i){ - int connect = 0; - for(int e:edges[i]) connect+=e; - vec.push_back({i+1,connect}); - } - // 邊緣點權重為1 開始,也連接的從連接少的開始給點知權重 - sort(vec.begin(), vec.end(), [](vector&a, vector&b){ - return a[1]>b[1]; - }); - int w = N; - // 分配頂點權重 - for(int i=0;i &a, vector &b){ - return a[0] 4 ‐> 7 ‐> 8 ‐> 9 -2016 -[‐1, 2, 3] -[4, 5, ‐6] -[7, 8, 9] -‐1 ‐> 4 ‐> 5 ‐> ‐6 ‐> 9 -1080 -``` - -- Leetcode 1594. Maximum Non Negative Product in a Matrix - -[ans](https://www.byte-by-byte.com/matrixproduct/) - - -4. Find Duplicates -Question: Given an array of integers where each value 1 <= x <= len(array), write a function that finds all the duplicates in the array. - -``` - -dups([1, 2, 3]) = [] -dups([1, 2, 2]) = [2] -dups([3, 3, 3]) = [3] -dups([2, 1, 2, 1]) = [1, 2] - -``` - -- Leetcode 287. Find the Duplicate Number -- Leetcode 442. Find All Duplicates in an Array - -[ans](https://www.byte-by-byte.com/findduplicates/) - -5. Consecutive Array* - -Question: Given an unsorted array, find the length of the longest sequence of consecutive numbers in the array. - -``` -consecutive([4, 2, 1, 6, 5]) = 3, [4, 5, 6] -consecutive([5, 5, 3, 1]) = 1, [1], [3], or [5] - -``` - -- Leetcode 674. Longest Continuous Increasing Subsequence -- Leetcode 523. Continuous Subarray Sum - -[ans](https://www.byte-by-byte.com/consecutivearray/) - - -6. Zero Matrix -Question: Given a boolean matrix, update it so that if any cell is true, all the cells in that row and column are true. - -``` -[true, false, false] [true, true, true ] -[false, false, false] ‐> [true, false, false] -[false, false, false] [true, false, false] -``` - -- Leetcode 733. Flood Fill -- Leetcode 73. Set Matrix Zeroes - -[ans](https://www.byte-by-byte.com/zeromatrix/) - -7. Square Submatrix -Question: Given a 2D array of 1s and 0s, find the largest square subarray of all 1s. - -``` -Given a 2D array of 1s and 0s, find the largest square subarray of all 1s. -``` - -- Leetcode 221. Maximal Square -- Leetcode 1277. Count Square Submatrices with All Ones - -[ans](https://www.byte-by-byte.com/squaresubmatrix/) - - - -8. Merge K Arrays* -Question: Given k sorted arrays, merge them into a single sorted array. - -``` -merge({{1, 4, 7},{2, 5, 8},{3, 6, 9}}) = {1, 2, 3, 4, 5, 6, 7, 8, 9} -``` ->Hint: priority queue store K array information - -[ans](https://www.byte-by-byte.com/mergekarrays/) - - -9. Matrix Search - -Question: Given an n x m array where all rows and columns are in sorted order, write a function to determine whether the array contains an element x. - -``` -contains([1, 2, 3, 4] - [5, 6, 7, 8] - [9, 10, 11, 12]) = True - -``` ->Hint : start from 左上或右下角 - -- Leetcode 74. Search a 2D Matrix -- Leetcode 240. Search a 2D Matrix II - - -[ans](https://www.byte-by-byte.com/matrixsearch/) - - - -10. Merge Arrays -Given 2 sorted arrays, A and B, where A is long enough to hold the contents of A and B, write a function to copy the contents of B into A without using any buffer or additional memory. - - -``` -A = {1,3,5,0,0,0} -B = {2,4,6} -mergeArrays(A, B) -A = {1,2,3,4,5,6} -``` - -- Leetcode 88. Merge Sorted Array - -[ans](https://www.byte-by-byte.com/mergearrays/) - -11. Zero Sum Subarray* -Question: Given an array, write a function to find any subarray that sums to zero, if one exists. - - -``` -zeroSum({1, 2, ‐5, 1, 2, ‐1}) = [2, ‐5, 1, 2] -``` - ->Hint: hash table, sum mapping index - -- Leetcode 560. Subarray Sum Equals K - -[ans](https://www.byte-by-byte.com/zerosum/) - -12. Permutations* -Question: Write a function that returns all permutations of a given list. - -``` -permutations({1, 2, 3}) -[1, 2, 3] -[1, 3, 2] -[2, 1, 3] -[2, 3, 1] -[3, 1, 2] -[3, 2, 1] -``` ->Hint : swap - -- Leetcode 46. Permutations -- Leetcode 47. Permutations II -[ans](https://www.byte-by-byte.com/permutations/) - - -13. N Stacks* -Question: Implement N > 0 stacks using a single array to store all stack data (you may use auxiliary arrays in your stack object, but all of the objects in all of the stacks must be in the same array). No stack should be full unless the entire array is full. - -``` -N = 3; -capacity = 10; -Stacks stacks = new Stacks(N, capacity); -stacks.put(0, 10); -stacks.put(2, 11); -stacks.pop(0) = 10; -stacks.pop(2) = 11; - -``` - ->Hint: 用3個array維護 - -[ans](https://www.byte-by-byte.com/nstacks/) - - -14. Anagrams - -Question: Given two strings, write a function to determine whether they are anagrams. - -``` -isAnagram("", "") = true -isAnagram("A", "A") = true -isAnagram("A", "B") = false -isAnagram("ab", "ba") = true -isAnagram("AB", "ab") = true -``` - -- Leetcode 242. Valid Anagram -- Leetcode 49. Group Anagrams - -[ans](https://www.byte-by-byte.com/anagrams/) - - -### Graph 15-16 - -15. Build Order* - -Question: Given a list of packages that need to be built and the dependencies for each package, determine a valid order in which to build the packages. - -``` -0: -1: 0 -2: 0 -3: 1, 2 -4: 3 -output: 0, 1, 2, 3, 4 -``` - -[ans](https://www.byte-by-byte.com/buildorder/) - -16. Shortest Path* - -Question: Given a directed graph, find the shortest path between two nodes if one exists. - - - - -``` -shortestPath(2, 3) = 2 ‐> 5 ‐> 4 ‐> 3 - -``` - -### Recursion 17-26 - -17. Random Binary Tree - -Question: Implement a binary tree with a method getRandomNode() that returns a random node. - -```graphviz -digraph hierarchy { - - nodesep=1.0 // increases the separation between nodes - - node [color=Red,fontname=Courier,shape=box] //All nodes will this shape and colour - edge [color=Blue, style=dashed] //All the lines look like this - 5->{2 7} - 2->{1 3} - 7->{6 8} - {rank=same;1 3 6 8} // Put them on the same level -} - - -``` -``` -getRandomNode() = 5 -getRandomNode() = 8 -getRandomNode() = 1 -``` - - -[ans](https://www.byte-by-byte.com/randombinarytree/) - -18. Lowest Common Ancestor* -Question: Given two nodes in a binary tree, write a function to find the lowest common ancestor. - -```graphviz -digraph hierarchy { - - nodesep=1.0 // increases the separation between nodes - - node [color=Red,fontname=Courier,shape=box] //All nodes will this shape and colour - edge [color=Blue, style=dashed] //All the lines look like this - 1->{2 3} - 2->{4 5} - 3->{6 7} - -} - -``` - -``` - -lcs(4, 3) = 1 -lcs(6, 7) = 3 -``` - -- Leetcode 236. Lowest Common Ancestor of a Binary Treeans - -[ans](https://www.byte-by-byte.com/lowestcommonancestor/) - - - -19. Sum* - -Question: Given two integers, write a function to sum the numbers without using any arithmetic operators. - ->Hint: xor -- Leetcode 371. Sum of Two Integers - - -[ans](https://www.byte-by-byte.com/sum/) - - -20. Reverse Stack* - -Question: Given a stack, reverse the items without creating any additional data structures. - -``` -reverse(1‐>2‐>3) = 3‐>2‐>1 -``` - -[ans](https://www.byte-by-byte.com/reversestack/) - -21. Tree to Doubly Linked List* - -Question: Given a tree, write a function to convert it into a circular doubly linked list from left to right by only modifying the existing pointers. - - -```graphviz -digraph hierarchy { - - nodesep=1.0 // increases the separation between nodes - - node [color=Red,fontname=Courier,shape=box] //All nodes will this shape and colour - edge [color=Blue, style=dashed] //All the lines look like this - 1->{2 3} - 2->{4 5} - 3->{6 7} -} - -``` - -``` -<‐ 4 <‐> 2 <‐> 5 <‐> 1 <‐> 6 <‐> 3 <‐> 7 ‐> - -``` - -- Leetcode 426. Convert Binary Search Tree to Sorted Doubly Linked List - -[ans](https://www.byte-by-byte.com/treetolist/) - - -22. Longest Consecutive Branch* - -Question: Given a tree, write a function to find the length of the longest branch of nodes in increasing consecutive order. - - -- Leetcode 298. Binary Tree Longest Consecutive Sequence -- Leetcode 549. Binary Tree Longest Consecutive Sequence II - -[ans](https://www.byte-by-byte.com/longestbranch/) - - - -23. Print Reversed Linked List - -Question: Given a linked list, write a function that prints the nodes of the list in reverse order. - -``` -printReversedList(1 ‐> 2 ‐> 3) -3 -2 -1 -``` -- Leetcode 206. Reverse Linked List - - -[ans](https://www.byte-by-byte.com/printreversedlist/) - - - -24. Balanced Binary Tree* - -Question: Given a binary tree, write a function to determine whether the tree is balanced. - -- Leetcode 110. Balanced Binary Tree - - -[ans](https://www.byte-by-byte.com/balancedtree/) - - -25. Binary Search Tree Verification* - -Question: Given a binary tree, write a function to test if the tree is a binary search tree. - - -- Leetcode 98. Validate Binary Search Tree - - -[ans](https://www.byte-by-byte.com/binarysearchtree/) - -26. Smallest Change* - -Question: Given an input amount of change x, write a function to determine the minimum number of coins required to make that amount of change. - -- Leetcode 322. Coin Change ->Hint: dp - -[ans](https://www.byte-by-byte.com/smallestchange/) - - -### Stack 27-31 - -27. Inorder Traversal* - -Question: Given a binary search tree, print out the elements of the tree in order without using recursion. - ->Hint: stack - -- Leetcode 94. Binary Tree Inorder Traversal -- Leetcode 144. Binary Tree Preorder Traversal -- Leetcode 145. Binary Tree Postorder Traversal - - - -[ans](https://www.byte-by-byte.com/inordertraversal/) - - -28. Sort Stacks* - -Question: Given a stack, sort the elements in the stack using one additional stack. - -``` -sort([1, 3, 2, 4]) = [1, 2, 3, 4] -``` ->Hint: two level loop -[ans](https://www.byte-by-byte.com/sortstacks/) - -29. Stack from Queues - -Question: Implement a LIFO stack with basic functionality (push and pop) using FIFO queues to store the data. - - -- Leetcode 225. Implement Stack using Queues -- Leetcode 232. Implement Queue using Stacks - -[ans](https://www.byte-by-byte.com/stackfromqueues/) - - -30. Palindromes - -Question: Given a linked list, write a function to determine whether the list is a palindrome. - -``` -palindrome(1 ‐> 2 ‐> 3) = false -palindrome(1 ‐> 2 ‐> 1) = true - -``` - - -- Leetcode 234. Palindrome Linked List -- Leetcode 9. Palindrome Number -- Leetcode 125. Valid Palindrome - - -[ans](https://www.byte-by-byte.com/palindromes/) - - -31. Max Stacks* - -Question: Implement a LIFO stack that has a push(), pop(), and max() function, where max() returns the maximum value in the stack. All of these functions should run in O(1) time. - -``` -push(1) -max() = 1 -push(2) -max() = 2 -push(1) -max() = 2 -pop() = 1 -max() = 2 -pop() = 2 -max() = 1 -``` - -- Leetcode 155. Min Stack - -[ans](https://www.byte-by-byte.com/maxstack/) - - -### Bit Manipulation 32-37 - -32. Two Missing Numbers* - -Question: Given an array containing all the numbers from 1 to n except two, find the two missing numbers. - -``` -missing([4, 2, 3]) = 1, 5 -``` - -- Leetcode 268. Missing Number -- Leetcoede - -[ans](https://www.byte-by-byte.com/twomissingnumbers/) - - -33. Big Int Modules* -Question: Given a list of bytes a, each representing one byte of a larger integer (ie. {0x12, 0x34, 0x56, 0x78}represents the integer 0x12345678), and an integer b, find a % b. - -``` -mod({0x03, 0xED}, 10) = 5 -``` - -[ans](https://www.byte-by-byte.com/bigintmod/) - - -34. Swap Variables* -Question: Given two integers, write a function that swaps them without using any temporary variables. - -```java -public void swap(int x, int y) { - x = x + y; - y = x - y; - x = x - y; -} - -public void swap(int x, int y) { - x = x ^ y; - y = x ^ y; - x = x ^ y; -} -``` - -[ans](https://www.byte-by-byte.com/swapvariables/) - - -35. Gray Code* -Question: Given two integers, write a function to determine whether or not their binary representations differ by a single bit. - -``` -gray(0, 1) = true -gray(1, 2) = false -``` - -> Hint: (x & (x-1)) == 0 -- Leetcode 89. Gray Code - -[ans](https://www.byte-by-byte.com/graycode/) - - -36. Rotate Bits* -Question: Given a number, write a function to rotate the bits (ie circular shift). -``` -rotate(0xFFFF0000, 8) = 0x00FFFF00 -rotate(0x13579BDF, 12) = 0xBDF13579 -rotate(0b10110011100011110000111110000000, 17) = -0b00011111000000010110011100011110 - -``` - -[ans](https://www.byte-by-byte.com/rotatebits/) - - -37. Number of Ones in a Binary Number - -Question: Given an integer, write a function to compute the number of ones in the binary representation of the number. - -- Leetcode 191. Number of 1 Bits - - -[ans](https://www.byte-by-byte.com/onesinbinary/) - -### Linked List 38-44 - -38. Linked List Cycles - -Question: Given a linked list, determine whether it contains a cycle. - - ->Hint: slow-fast pointer - -- Leetcode 141. Linked List Cycle -- Leetcode 142. Linked List Cycle II - -[ans](https://www.byte-by-byte.com/listcycles/) - - -39. Random Linked List* -Question: Given a linked list where each node has two pointers, one to the next node and one to a random node in the list, clone the linked list. - -- Leetcode 138. Copy List with Random Pointer - -[ans](https://www.byte-by-byte.com/randomlinkedlist/) - -40. Dedup Linked List* - -Question: Given an unsorted linked list, write a function to remove all the duplicates. - -``` -dedup(1 ‐> 2 ‐> 3 ‐> 2 ‐> 1) = 1 ‐> 2 ‐> 3 -``` -- LeetCode 1836. Remove Duplicates From an Unsorted Linked List - -[ans](https://www.byte-by-byte.com/deduplinkedlist/) - - -41. Split a Linked List* - -Question: Given a linked list, write a function to split the list into two equal halves. - -``` -divide(1 ‐> 2 ‐> 3 ‐> 4) = 1 ‐> 2, 3 ‐> 4 -divide(1 ‐> 2 ‐> 3 ‐> 4 ‐> 5) = 1 ‐> 2 ‐> 3, 4 ‐> 5 - -``` - -- Leetcode 725. Split Linked List in Parts - -[ans](https://www.byte-by-byte.com/splitlinkedlist/) - - - -42. Nth to the Last Element* -Question: Given a linked list, and an input n, write a function that returns the nth-to-last element of the linked list. - -> Hint: two pointer -- Leetcode 19. Remove Nth Node From End of List - - -[ans](https://www.byte-by-byte.com/nthtolastelement/) - - - -43. Three Sum - - -Question: Given a list of integers, write a function that returns all sets of 3 numbers in the list, a, b, and c, so that a + b + c == 0. - - -``` -threeSum({‐1, 0, 1, 2, ‐1, ‐4}) -[‐1, ‐1, 2] -[‐1, 0, 1] -``` - -- Leetcode 15. 3Sum -- Leetcode 18. 4Sum - - -[ans](https://www.byte-by-byte.com/threesum/) - -44. Tree Level Order - -Question: Given a tree, write a function that prints out the nodes of the tree in level order. - - -```graphviz -digraph hierarchy { - - nodesep=1.0 // increases the separation between nodes - - node [color=Red,fontname=Courier,shape=box] //All nodes will this shape and colour - edge [color=Blue, style=dashed] //All the lines look like this - 1->{2 3} - 2->{4 5} - 3->{6 7} - {rank=same;4 5 6 7} // Put them on the same level -} - - - -``` - - -``` -traverse(tree) = 1 2 3 4 5 6 7 -``` - -- Leetcode 102. Binary Tree Level Order Traversal -- Leetcode 107. Binary Tree Level Order Traversal II - - -[ans](https://www.byte-by-byte.com/treelevelorder/) - - - -### String 45-50 - -45. Autocomplete* -Question: Write an autocomplete class that returns all dictionary words with a given prefix. - -``` -dict: {"abc", "acd", "bcd", "def", "a", "aba"} -prefix: "a" ‐> "abc", "acd", "a", "aba" -prefix: "b" ‐> "bcd" -``` - -- Leetcode 642. Design Search Autocomplete System - -[ans](https://www.byte-by-byte.com/autocomplete/) - - -46. String Deletion* -Question: Given a string and a dictionary HashSet, write a function to determine the minimum number of characters to delete to make a word. - -``` -dictionary: [“a”, “aa”, “aaa”] -query: “abc” -output: 2 -``` -[ans](https://www.byte-by-byte.com/stringdeletion/) - - -47. Longest Common Substring -Question: Given two strings, write a function that returns the longest common substring. - -``` -longestSubstring("ABAB", "BABA") = "ABA" -``` - -- Leetcode 1143. Longest Common Subsequence - -[ans](https://www.byte-by-byte.com/longestsubstring/) - - -48. String Compression* - - -Question: Given a string, write a function to compress it by shortening every sequence of the same character to that character followed by the number of repetitions. If the compressed string is longer than the original, you should return the original string. - -``` -compress(“a”) = "a" -compress(“aaa”) = "a3" -compress(“aaabbb”) = "a3b3" -compress(“aaabccc”) = "a3b1c3" -``` - -- Leetcode 443. String Compression - - - -[ans](https://www.byte-by-byte.com/stringcompression/) - -49. Fibonacci Number -Question: Given an integer n, write a function to compute the nth Fibonacci number. - -``` -fibonacci(1) = 1 -fibonacci(5) = 5 -fibonacci(10) = 55 -``` - -- Leetcode 509. Fibonacci Number - -[ans](https://www.byte-by-byte.com/fibonacci/) - -50. Priority Queue - -Question: Implement a Priority Queue - - -[ans](https://www.byte-by-byte.com/priorityqueue/) \ No newline at end of file diff --git a/C/1009_ComplementofBase10Integer.c b/C/1009_ComplementofBase10Integer.c deleted file mode 100644 index 2c83551..0000000 --- a/C/1009_ComplementofBase10Integer.c +++ /dev/null @@ -1,32 +0,0 @@ - - -int bitwiseComplement(int n) -{ - // option 1 - // unsigned mask = ~0; - // if(n==0) return 1; - // int i=31; - // while((n>>i)==0) i--; - // mask = mask<<(i+1); - // mask = ~mask; - // return n ^ mask; - - // option 1 - if (n == 0) - return 1; - int num = n; - int i = 0; - while (n) - { - i++; - n >>= 1; - } - int mask = 0; - while (i) - { - mask <<= 1; - mask += 1; - i--; - } - return num ^ mask; -} \ No newline at end of file diff --git a/C/105_ConstructBinaryTreefromPreorderandInorderTraversal.c b/C/105_ConstructBinaryTreefromPreorderandInorderTraversal.c deleted file mode 100644 index 88582c6..0000000 --- a/C/105_ConstructBinaryTreefromPreorderandInorderTraversal.c +++ /dev/null @@ -1,35 +0,0 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * struct TreeNode *left; - * struct TreeNode *right; - * }; - */ - -struct TreeNode *build(int *preorder, int pl, int pr, int *inorder, int il, int ir) -{ - - if (il > ir || pl > pr) - return NULL; - - struct TreeNode *root = malloc(sizeof(struct TreeNode)); - root->val = preorder[pl]; - int idx = -1; - for (int i = il; i <= ir; ++i) - { - if (inorder[i] == preorder[pl]) - { - idx = i; - break; - } - } - root->left = build(preorder, pl + 1, pl + idx - il, inorder, il, idx - 1); - root->right = build(preorder, pl + 1 + idx - il, pr, inorder, idx + 1, ir); - return root; -} - -struct TreeNode *buildTree(int *preorder, int preorderSize, int *inorder, int inorderSize) -{ - return build(preorder, 0, preorderSize - 1, inorder, 0, inorderSize - 1); -} \ No newline at end of file diff --git a/C/106_ConstructBinaryTreefromInorderandPostorderTraversal.c b/C/106_ConstructBinaryTreefromInorderandPostorderTraversal.c deleted file mode 100644 index 53b0267..0000000 --- a/C/106_ConstructBinaryTreefromInorderandPostorderTraversal.c +++ /dev/null @@ -1,34 +0,0 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * struct TreeNode *left; - * struct TreeNode *right; - * }; - */ - -struct TreeNode *build(int *inorder, int il, int ir, int *postorder, int pl, int pr) -{ - if (pl > pr || il > ir) - return NULL; - int idx = -1, val = -1; - for (int i = il; i <= ir; ++i) - { - if (inorder[i] == postorder[pr]) - { - idx = i; - break; - } - } - - struct TreeNode *root = malloc(sizeof(struct TreeNode)); - root->val = postorder[pr]; - root->left = build(inorder, il, idx - 1, postorder, pl, pl + idx - il - 1); - root->right = build(inorder, idx + 1, ir, postorder, pl + idx - il, pr - 1); - return root; -} -struct TreeNode *buildTree(int *inorder, int inorderSize, int *postorder, int postorderSize) -{ - - return build(inorder, 0, inorderSize - 1, postorder, 0, postorderSize - 1); -} \ No newline at end of file diff --git a/C/1143_LongestCommonSubsequence.c b/C/1143_LongestCommonSubsequence.c deleted file mode 100644 index edb0cc6..0000000 --- a/C/1143_LongestCommonSubsequence.c +++ /dev/null @@ -1,29 +0,0 @@ -#define max(a, b) ((a > b) ? a : b) - -int longestCommonSubsequence(char *text1, char *text2) -{ - - // a c e - // 0 0 0 - //a 0 1 1 1 - //b 0 1 1 1 - //c 1 2 2 - //d 1 2 2 - //e 1 2 3 - - int n = strlen(text1), m = strlen(text2); - int **dp = calloc(n + 1, sizeof(int *)); - for (int i = 0; i <= n; ++i) - dp[i] = calloc(m + 1, sizeof(int)); - for (int i = 1; i <= n; ++i) - { - for (int j = 1; j <= m; ++j) - { - if (text1[i - 1] == text2[j - 1]) - dp[i][j] = dp[i - 1][j - 1] + 1; - else - dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]); - } - } - return dp[n][m]; -} \ No newline at end of file diff --git a/C/1342_NumberofStepstoReduceaNumbertoZero.c b/C/1342_NumberofStepstoReduceaNumbertoZero.c deleted file mode 100644 index bd8657d..0000000 --- a/C/1342_NumberofStepstoReduceaNumbertoZero.c +++ /dev/null @@ -1,25 +0,0 @@ - - -int numberOfSteps(int num) -{ - - // base case - // if(num==0) return 0; - - // if(num%2==0) return numberOfSteps(num/2)+1; - // else return numberOfSteps(num-1)+1; - - // bit manipulation - // 1000 => 4 - // 1110 => 6 - // 遇到1 +2 遇到0 +1 ,最後減一 - int ret = 0; - if (!num) - return 0; - while (num) - { - ret += (num & 1 ? 2 : 1); - num >>= 1; - } - return ret - 1; -} \ No newline at end of file diff --git a/C/1356_SortIntegersbyTheNumberof1Bits.c b/C/1356_SortIntegersbyTheNumberof1Bits.c deleted file mode 100644 index 568a2ad..0000000 --- a/C/1356_SortIntegersbyTheNumberof1Bits.c +++ /dev/null @@ -1,44 +0,0 @@ - - -/** - * Note: The returned array must be malloced, assume caller calls free(). - */ -int count(int n) -{ - int ret = 0; - while (n) - { - ret++; - n &= n - 1; - } - return ret; -} -void swap(int *a, int *b) -{ - int temp = *a; - *a = *b; - *b = temp; -} -int *sortByBits(int *arr, int arrSize, int *returnSize) -{ - // bubble sort - *returnSize = arrSize; - for (int i = 0; i < arrSize - 1; ++i) - { - for (int j = 0; j < arrSize - 1; ++j) - { - if (count(arr[j]) == count(arr[j + 1])) - { - if (arr[j] > arr[j + 1]) - { - swap(&arr[j], &arr[j + 1]); - } - } - else if (count(arr[j]) > count(arr[j + 1])) - { - swap(&arr[j], &arr[j + 1]); - } - } - } - return arr; -} \ No newline at end of file diff --git a/C/1486_XOROperationinanArray.c b/C/1486_XOROperationinanArray.c deleted file mode 100644 index 0c4506f..0000000 --- a/C/1486_XOROperationinanArray.c +++ /dev/null @@ -1,14 +0,0 @@ - - -int xorOperation(int n, int start) -{ - - int ret = start; - int a = start + 2; - for (int i = 1; i < n; ++i) - { - ret ^= a; - a += 2; - } - return ret; -} \ No newline at end of file diff --git a/C/167_TwoSumII-Inputarrayissorted.c b/C/167_TwoSumII-Inputarrayissorted.c deleted file mode 100644 index 7b9780c..0000000 --- a/C/167_TwoSumII-Inputarrayissorted.c +++ /dev/null @@ -1,26 +0,0 @@ - - -/** - * Note: The returned array must be malloced, assume caller calls free(). - */ -int *twoSum(int *numbers, int numbersSize, int target, int *returnSize) -{ - - int i = 0, j = numbersSize - 1; - int *ret = calloc(*returnSize = 2, sizeof(int)); - - while (i < j) - { - if (target == numbers[i] + numbers[j]) - { - ret[0] = i + 1; - ret[1] = j + 1; - return ret; - } - else if (target < numbers[i] + numbers[j]) - j--; - else - i++; - } - return ret; -} \ No newline at end of file diff --git a/C/1749_MaximumAbsoluteSumofAnySubarray.c b/C/1749_MaximumAbsoluteSumofAnySubarray.c deleted file mode 100644 index 0a47326..0000000 --- a/C/1749_MaximumAbsoluteSumofAnySubarray.c +++ /dev/null @@ -1,28 +0,0 @@ -#define max(a, b) ((a > b) ? a : b) -#define min(a, b) ((a < b) ? a : b) - -int maxAbsoluteSum(int *nums, int numsSize) -{ - - // 1 -3 2 3 -4 - //mx 1 -2 2 5 1 - //mn 1 -3 -1 2 -2 - //ans(abs) - - // 2 -5 1 -4 3 -2 - //mx 2 -3 1 -3 3 1 - //mn 2 -5 -4 -8 -5 -7 - //abs - int *mx = calloc(numsSize, sizeof(int)); - int *mn = calloc(numsSize, sizeof(int)); - int ans = max(nums[0], -nums[0]); - mx[0] = nums[0], mn[0] = nums[0]; - for (int i = 1; i < numsSize; ++i) - { - mx[i] = max(nums[i] + mx[i - 1], nums[i]); - mn[i] = min(nums[i] + mn[i - 1], nums[i]); - ans = max(ans, max(mx[i], -mx[i])); - ans = max(ans, max(mn[i], -mn[i])); - } - return ans; -} \ No newline at end of file diff --git a/C/189_RotateArray.c b/C/189_RotateArray.c deleted file mode 100644 index c542d9f..0000000 --- a/C/189_RotateArray.c +++ /dev/null @@ -1,35 +0,0 @@ -void swap(int *a, int *b) -{ - int temp = *a; - *a = *b; - *b = temp; -} -void reverse(int *nums, int i, int j) -{ - while (i < j) - { - swap(&nums[i++], &nums[j--]); - } -} -void rotate(int *nums, int numsSize, int k) -{ - - // option 1 cheap - // int *ret = calloc(numsSize, sizeof(int)); - // k = numsSize - k%numsSize; - // for(int i=0;inext) return head; - // struct ListNode *pre = (struct ListNode *)malloc(sizeof(struct ListNode)) ; - // pre->next = head; - // struct ListNode *cur = head; - // while(cur->next){ - // struct ListNode * temp = cur->next; - // cur->next = temp->next; - // temp->next = pre->next; - // pre->next = temp; - - // } - // return pre->next; - - if (!head) - return head; - if (!head->next) - return head; - struct ListNode *node = reverseList(head->next); - head->next->next = head; - head->next = NULL; - return node; -} \ No newline at end of file diff --git a/C/209_MinimumSizeSubarraySum.c b/C/209_MinimumSizeSubarraySum.c deleted file mode 100644 index d4df436..0000000 --- a/C/209_MinimumSizeSubarraySum.c +++ /dev/null @@ -1,22 +0,0 @@ -#define min(a, b) ((a < b) ? a : b) - -int minSubArrayLen(int target, int *nums, int numsSize) -{ - // slide window - int l = 0, r = 0; - int len = numsSize + 1; - int cur = 0; - while (r < numsSize) - { - int c = nums[r++]; - cur += c; - while (cur >= target) - { - printf("%d\t%d\n", l, r); - len = min(len, r - l); - int d = nums[l++]; - cur -= d; - } - } - return len == numsSize + 1 ? 0 : len; -} \ No newline at end of file diff --git a/C/20_ValidParentheses.c b/C/20_ValidParentheses.c deleted file mode 100644 index af0d7b2..0000000 --- a/C/20_ValidParentheses.c +++ /dev/null @@ -1,21 +0,0 @@ - - -bool isValid(char * s){ - char * stack = malloc(sizeof(char)*strlen(s)); - int n = strlen(s); - int idx = 0; - for(int i=0 ; ival < l2->val) - { - ret->next = l1; - l1 = l1->next; - } - else - { - ret->next = l2; - l2 = l2->next; - } - - ret = ret->next; - } - if (l1) - ret->next = l1; - if (l2) - ret->next = l2; - return ans->next; -} \ No newline at end of file diff --git a/C/221_MaximalSquare.c b/C/221_MaximalSquare.c deleted file mode 100644 index 283c61d..0000000 --- a/C/221_MaximalSquare.c +++ /dev/null @@ -1,36 +0,0 @@ -#define max(a, b) ((a > b) ? a : b) -#define min(a, b) ((a < b) ? a : b) - -int maximalSquare(char **matrix, int matrixSize, int *matrixColSize) -{ - - // 1 0 1 0 0 1 0 1 0 0 - // 1 0 1 1 1 1 0 1 1 1 - // 1 1 1 1 1 1 1 1 2 2 - // 1 0 0 1 0 1 0 0 1 0 - - int **dp = malloc(matrixSize * sizeof(int *)); - for (int i = 0; i < matrixSize; ++i) - dp[i] = malloc(*(matrixColSize + i) * sizeof(int)); - int ret = 0; - for (int i = 0; i < matrixSize; ++i) - { - for (int j = 0; j < *(matrixColSize + i); ++j) - { - if (matrix[i][j] == '0') - dp[i][j] = 0; - else - { - if (i == 0 || j == 0) - dp[i][j] = matrix[i][j] - '0'; - else - dp[i][j] = min(dp[i - 1][j - 1], min(dp[i - 1][j], dp[i][j - 1])) + 1; - } - ret = max(ret, dp[i][j]); - } - } - - for (int i = 0; i < matrixSize; ++i) - free(dp[i]); - return ret * ret; -} \ No newline at end of file diff --git a/C/237_DeleteNodeinaLinkedList.c b/C/237_DeleteNodeinaLinkedList.c deleted file mode 100644 index f4b5206..0000000 --- a/C/237_DeleteNodeinaLinkedList.c +++ /dev/null @@ -1,12 +0,0 @@ -/** - * Definition for singly-linked list. - * struct ListNode { - * int val; - * struct ListNode *next; - * }; - */ -void deleteNode(struct ListNode *node) -{ - node->val = node->next->val; - node->next = node->next->next; -} \ No newline at end of file diff --git a/C/242_ValidAnagram.c b/C/242_ValidAnagram.c deleted file mode 100644 index 712aae1..0000000 --- a/C/242_ValidAnagram.c +++ /dev/null @@ -1,18 +0,0 @@ - - -bool isAnagram(char *s, char *t) -{ - - int *dict = calloc(26, sizeof(int)); - int m = strlen(t), n = strlen(s); - for (int i = 0; i < m; ++i) - dict[t[i] - 'a']++; - for (int i = 0; i < n; ++i) - dict[s[i] - 'a']--; - for (int i = 0; i < 26; ++i) - { - if (dict[i] != 0) - return false; - } - return true; -} \ No newline at end of file diff --git a/C/268_MissingNumber.c b/C/268_MissingNumber.c deleted file mode 100644 index 0765639..0000000 --- a/C/268_MissingNumber.c +++ /dev/null @@ -1,14 +0,0 @@ - - -int missingNumber(int *nums, int numsSize) -{ - // maybe overflow - // int total = (numsSize+1)*numsSize/2; - // for(int i=0;i b) ? a : b) - -int lengthOfLIS(int *nums, int numsSize) -{ - - // dp - // 10 9 2 5 3 7 101 18 - // 1 1 1 1 1 1 1 1 - // 1 1 1 2 2 3 4 4 - - int *dp = calloc(numsSize, sizeof(int)); - for (int i = 0; i < numsSize; ++i) - *(dp + i) = 1; - int ret = dp[0]; - for (int i = 1; i < numsSize; ++i) - { - for (int j = 0; j < i; ++j) - { - if (nums[i] > nums[j]) - dp[i] = max(dp[j] + 1, dp[i]); - } - ret = max(ret, dp[i]); - } - free(dp); - return ret; -} \ No newline at end of file diff --git a/C/338_CountingBits.c b/C/338_CountingBits.c deleted file mode 100644 index 5a7fb8c..0000000 --- a/C/338_CountingBits.c +++ /dev/null @@ -1,25 +0,0 @@ - - -/** - * Note: The returned array must be malloced, assume caller calls free(). - */ -int count(int n){ - int ret =0; - while(n){ - ret++; - n &= n-1; - } - return ret; -} -int* countBits(int n, int* returnSize){ - // O(nlogn) time - *returnSize = n+1; - int *ret = calloc(n+1, sizeof(int)); - for(int i=0;i<=n;++i) *(ret+i) = count(i); - return ret; - - - - - -} \ No newline at end of file diff --git a/C/342_PowerofFour.c b/C/342_PowerofFour.c deleted file mode 100644 index 4584751..0000000 --- a/C/342_PowerofFour.c +++ /dev/null @@ -1,8 +0,0 @@ - - -bool isPowerOfFour(int n){ - if(n==0) return false; - while(n%4==0) n>>=2; - return n==1; - -} \ No newline at end of file diff --git a/C/344_ReverseString.c b/C/344_ReverseString.c deleted file mode 100644 index b1e7df8..0000000 --- a/C/344_ReverseString.c +++ /dev/null @@ -1,17 +0,0 @@ - -void swap(char *s, char *t) -{ - char temp = *s; - *s = *t; - *t = temp; -} -void reverseString(char *s, int sSize) -{ - int l = 0, r = sSize - 1; - while (l < r) - { - swap(&s[l], &s[r]); //swap(&*(s+l), &*(s+r)); - l++; - r--; - } -} \ No newline at end of file diff --git a/C/349*_IntersectionofTwoArrays.c b/C/349*_IntersectionofTwoArrays.c deleted file mode 100644 index 7d36931..0000000 --- a/C/349*_IntersectionofTwoArrays.c +++ /dev/null @@ -1,68 +0,0 @@ - - -/** - * Note: The returned array must be malloced, assume caller calls free(). - */ - -void swap(int *a, int *b) -{ - int temp = *a; - *a = *b; - *b = temp; -} -int partition(int *nums, int l, int r) -{ - int pivot = nums[r]; - int i = l - 1; - for (int j = l; j < r; ++j) - { - if (nums[j] < pivot) - { - i++; - swap(&nums[j], &nums[i]); - } - } - i++; - swap(&nums[i], &nums[r]); - return i; -} -void quickSort(int *nums, int l, int r) -{ - if (l < r) - { - int pivot = partition(nums, l, r); - quickSort(nums, l, pivot - 1); - quickSort(nums, pivot + 1, r); - } -} -int *intersection(int *nums1, int nums1Size, int *nums2, int nums2Size, int *returnSize) -{ - quickSort(nums1, 0, nums1Size - 1); - quickSort(nums2, 0, nums2Size - 1); - - int *ret = NULL; - int count = 0; - int l = 0, r = 0; - while (l < nums1Size && r < nums2Size) - { - if (nums1[l] == nums2[r]) - { - ret = realloc(ret, sizeof(int) * (count + 1)); - ret[count] = nums1[l]; - count++; - - while (l < nums1Size - 1 && nums1[l] == nums1[l + 1]) - l++; - while (r < nums2Size - 1 && nums2[r] == nums2[r + 1]) - r++; - l++; - r++; - } - else if (nums1[l] < nums2[r]) - l++; - else - r++; - } - *returnSize = count; - return ret; -} \ No newline at end of file diff --git a/C/34_FindFirstandLastPositionofElementinSortedArray.c b/C/34_FindFirstandLastPositionofElementinSortedArray.c deleted file mode 100644 index b1e65f0..0000000 --- a/C/34_FindFirstandLastPositionofElementinSortedArray.c +++ /dev/null @@ -1,33 +0,0 @@ - - -/** - * Note: The returned array must be malloced, assume caller calls free(). - */ -int *searchRange(int *nums, int numsSize, int target, int *returnSize) -{ - - int l = 0, r = numsSize; - *returnSize = 2; - int *ret = malloc(2 * sizeof(int)); - // left bound - while (l < r) - { - int mid = l + (r - l) / 2; - if (nums[mid] == target) - r = mid; - else if (nums[mid] < target) - l = mid + 1; - else - r = mid; - } - if (l > numsSize - 1 || l < 0 || nums[l] != target) - { - ret[0] = -1, ret[1] = -1; - return ret; - } - ret[0] = l; - while (l < numsSize - 1 && nums[l + 1] == target) - l++; - ret[1] = l; - return ret; -} \ No newline at end of file diff --git a/C/350*_IntersectionofTwoArraysII.c b/C/350*_IntersectionofTwoArraysII.c deleted file mode 100644 index 7805351..0000000 --- a/C/350*_IntersectionofTwoArraysII.c +++ /dev/null @@ -1,68 +0,0 @@ - - -/** - * Note: The returned array must be malloced, assume caller calls free(). - */ - -void swap(int *a, int *b) -{ - int temp = *a; - *a = *b; - *b = temp; -} -int partition(int *nums, int l, int r) -{ - int pivot = nums[r]; - int i = l - 1; - for (int j = l; j < r; ++j) - { - if (nums[j] < pivot) - { - i++; - swap(&nums[j], &nums[i]); - } - } - i++; - swap(&nums[i], &nums[r]); - return i; -} -void quickSort(int *nums, int l, int r) -{ - if (l < r) - { - int pivot = partition(nums, l, r); - quickSort(nums, l, pivot - 1); - quickSort(nums, pivot + 1, r); - } -} -int *intersect(int *nums1, int nums1Size, int *nums2, int nums2Size, int *returnSize) -{ - - quickSort(nums1, 0, nums1Size - 1); - quickSort(nums2, 0, nums2Size - 1); - - int *ret = NULL; - int count = 0; - int l = 0, r = 0; - - while (l < nums1Size && r < nums2Size) - { - if (nums1[l] == nums2[r]) - { - ret = realloc(ret, sizeof(int) * (count + 1)); - ret[count] = nums1[l]; - count++; - - // while(l< nums1Size -1 && nums1[l]==nums1[l+1]) l++; - // while(r< nums2Size -1 && nums2[r] == nums2[r+1]) r++; - l++; - r++; - } - else if (nums1[l] < nums2[r]) - l++; - else - r++; - } - *returnSize = count; - return ret; -} \ No newline at end of file diff --git a/C/371_SumofTwoIntegers.c b/C/371_SumofTwoIntegers.c deleted file mode 100644 index b4cbcd0..0000000 --- a/C/371_SumofTwoIntegers.c +++ /dev/null @@ -1,19 +0,0 @@ - - -int getSum(int a, int b) -{ - long long sum = 0, carry = 0; - long long ret = 0; - for (int i = 0; i < 32; ++i) - { - sum = carry; - sum += (a & 1) + (b & 1); - carry = sum / 2; - sum %= 2; - - ret += sum << i; - a >>= 1; - b >>= 1; - } - return ret; -} \ No newline at end of file diff --git a/C/383_RansomNote.c b/C/383_RansomNote.c deleted file mode 100644 index c9fd440..0000000 --- a/C/383_RansomNote.c +++ /dev/null @@ -1,18 +0,0 @@ - - -bool canConstruct(char *ransomNote, char *magazine) -{ - - int *dict = calloc(26, sizeof(int)); - for (int i = 0; magazine[i] != '\0'; ++i) - { - dict[magazine[i] - 'a']++; - } - for (int i = 0; ransomNote[i] != '\0'; ++i) - { - if (dict[ransomNote[i] - 'a'] == 0) - return false; - dict[ransomNote[i] - 'a']--; - } - return true; -} \ No newline at end of file diff --git a/C/387_FirstUniqueCharacterinaString.c b/C/387_FirstUniqueCharacterinaString.c deleted file mode 100644 index 23d317b..0000000 --- a/C/387_FirstUniqueCharacterinaString.c +++ /dev/null @@ -1,18 +0,0 @@ - - -int firstUniqChar(char *s) -{ - // - int *ret = calloc(26, sizeof(int)); - ; - for (int i = 0; *(s + i) != '\0'; ++i) - { - ret[s[i] - 'a']++; - } - for (int i = 0; *(s + i) != '\0'; ++i) - { - if (ret[s[i] - 'a'] == 1) - return i; - } - return -1; -} \ No newline at end of file diff --git a/C/397*_IntegerReplacement.c b/C/397*_IntegerReplacement.c deleted file mode 100644 index 3faed7f..0000000 --- a/C/397*_IntegerReplacement.c +++ /dev/null @@ -1,21 +0,0 @@ - - -int integerReplacement(int n) -{ - long long t = n; - int ret = 0; - while (t > 1) - { - if (t % 2 == 0) - t >>= 1; - else if ((t + 1) % 4 == 0 && t != 3) - { - // 判斷某數加 1 後是 4 的倍數 - t++; - } - else - t--; - ret++; - } - return ret; -} \ No newline at end of file diff --git a/C/3_LongestSubstringWithoutRepeatingCharacters.c b/C/3_LongestSubstringWithoutRepeatingCharacters.c deleted file mode 100644 index afa808e..0000000 --- a/C/3_LongestSubstringWithoutRepeatingCharacters.c +++ /dev/null @@ -1,21 +0,0 @@ -#define max(a, b) ((a > b) ? a : b) - -int lengthOfLongestSubstring(char *s) -{ - int *window = calloc(128, sizeof(int)); - int n = strlen(s); - int l = 0, r = 0, ret = 0; - while (r < n) - { - char c = s[r++]; - window[c]++; - - while (window[c] > 1) - { - char d = s[l++]; - window[d]--; - } - ret = max(r - l, ret); - } - return ret; -} \ No newline at end of file diff --git a/C/405_ConvertaNumbertoHexadecimal.c b/C/405_ConvertaNumbertoHexadecimal.c deleted file mode 100644 index 027df1d..0000000 --- a/C/405_ConvertaNumbertoHexadecimal.c +++ /dev/null @@ -1,17 +0,0 @@ - - -char *toHex(int num) -{ - char dec2hex[] = "0123456789abcdef"; - char *ret = calloc(9, sizeof(char)); - char *p = ret + 8; - unsigned int x = num; - while (ret != p) - { - *(--p) = (dec2hex[x % 16]); - x >>= 4; - } - while (*p == '0' && *(p + 1) != '\0') - p++; - return p; -} \ No newline at end of file diff --git a/C/509_FibonacciNumber.c b/C/509_FibonacciNumber.c deleted file mode 100644 index 5aa1d2d..0000000 --- a/C/509_FibonacciNumber.c +++ /dev/null @@ -1,15 +0,0 @@ - - -int fib(int n){ - if(n==0) return 0; - if(n==1) return 1; - int a = 0, b = 1, c = 1; - for(int i=2;i<=n ;++i){ - c = a+b; - a = b; - b = c; - } - - return c; - -} \ No newline at end of file diff --git a/C/538_ConvertBSTtoGreaterTree.c b/C/538_ConvertBSTtoGreaterTree.c deleted file mode 100644 index 43e27e0..0000000 --- a/C/538_ConvertBSTtoGreaterTree.c +++ /dev/null @@ -1,31 +0,0 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution -{ -public: - void traverse(TreeNode *root, int *val) - { - if (!root) - return; - - traverse(root->right, val); - root->val += *val; - *val = root->val; - traverse(root->left, val); - } - TreeNode *convertBST(TreeNode *root) - { - int val = 0; - traverse(root, &val); - return root; - } -}; \ No newline at end of file diff --git a/C/53_MaximumSubarray.c b/C/53_MaximumSubarray.c deleted file mode 100644 index e5ad887..0000000 --- a/C/53_MaximumSubarray.c +++ /dev/null @@ -1,13 +0,0 @@ - -#define max(a, b) ((a > b) ? a : b) - -int maxSubArray(int *nums, int numsSize) -{ - int ret = 0, global = INT_MIN; - for (int i = 0; i < numsSize; ++i) - { - ret = max(ret + nums[i], nums[i]); - global = max(ret, global); - } - return global; -} \ No newline at end of file diff --git a/C/557_ReverseWordsinaStringIII.c b/C/557_ReverseWordsinaStringIII.c deleted file mode 100644 index 82c7ff2..0000000 --- a/C/557_ReverseWordsinaStringIII.c +++ /dev/null @@ -1,32 +0,0 @@ -void swap(char *s, char *t) -{ - char temp = *s; - *s = *t; - *t = temp; -} -void reverse(char *s, int l, int r) -{ - while (l < r) - swap(&s[l++], &s[r--]); -} - -char *reverseWords(char *s) -{ - - int len = strlen(s); - int p = 0; - while (*(s + p) == ' ') - p++; - for (int i = 0; i < len; ++i) - { - if (*(s + i) == ' ') - { - reverse(s, p, i - 1); - while (*(s + i) == ' ') - i++; - p = i; - } - } - reverse(s, p, len - 1); - return s; -} \ No newline at end of file diff --git a/C/567_PermutationinString.c b/C/567_PermutationinString.c deleted file mode 100644 index ffee9bf..0000000 --- a/C/567_PermutationinString.c +++ /dev/null @@ -1,30 +0,0 @@ - - -bool checkInclusion(char *s1, char *s2) -{ - - int *window = calloc(26, sizeof(int)); - int *dict = calloc(26, sizeof(int)); - int n = strlen(s2), m = strlen(s1); - for (int i = 0; i < m; ++i) - dict[s1[i] - 'a']++; - for (int i = 0; i < n; ++i) - { - window[s2[i] - 'a']++; - if (i >= m) - window[s2[i - m] - 'a']--; - - bool ret = true; - for (int j = 0; j < 26; ++j) - { - if (window[j] != dict[j]) - { - ret = false; - break; - } - } - if (ret) - return true; - } - return false; -} \ No newline at end of file diff --git a/C/62_UniquePaths.c b/C/62_UniquePaths.c deleted file mode 100644 index db5ca32..0000000 --- a/C/62_UniquePaths.c +++ /dev/null @@ -1,55 +0,0 @@ - - -int uniquePaths(int m, int n) -{ - int dp[m][n]; - // 1 1 1 1 1 1 1 - // 1 2 3 4 5 6 7 - // 1 3 6 10 15 21 28 - - for (int i = 0; i < m; ++i) - { - for (int j = 0; j < n; ++j) - dp[i][j] = 0; - } - - for (int j = 0; j < n; ++j) - dp[0][j] = 1; - for (int i = 0; i < m; ++i) - dp[i][0] = 1; - - for (int i = 1; i < m; ++i) - { - for (int j = 1; j < n; ++j) - { - dp[i][j] = dp[i - 1][j] + dp[i][j - 1]; - } - } - int ret = dp[m - 1][n - 1]; - return dp[m - 1][n - 1]; - - // version 2 pointer - int **dp ; - dp = calloc(m , sizeof(int*)); - for(int i=0 ;i b) ? a : b) - -char *addBinary(char *a, char *b) -{ - int carry = 0; - int i = strlen(a), j = strlen(b); - int k = max(i, j) + 2; - char *ret = calloc(k, sizeof(char)); - i--; - j--; - ret[--k] = '\0'; - while (i >= 0 || j >= 0) - { - int sum = carry; - if (i >= 0) - sum += (a[i--] - '0'); - if (j >= 0) - sum += (b[j--] - '0'); - - carry = sum / 2; - ret[--k] = sum % 2 + '0'; - } - if (carry) - { - ret[0] = '1'; - return ret; - } - else - return ret + 1; -} \ No newline at end of file diff --git a/C/693*_BinaryNumberwithAlternatingBits.c b/C/693*_BinaryNumberwithAlternatingBits.c deleted file mode 100644 index eedf59a..0000000 --- a/C/693*_BinaryNumberwithAlternatingBits.c +++ /dev/null @@ -1,17 +0,0 @@ - - -bool hasAlternatingBits(int n) -{ - int p = (n & 1); - n >>= 1; - while (n) - { - if ((n & 1) && p == 1) - return false; - else if ((n & 1) == 0 && p == 0) - return false; - p = (n & 1); - n >>= 1; - } - return true; -} \ No newline at end of file diff --git a/C/695*_MaxAreaofIsland.c b/C/695*_MaxAreaofIsland.c deleted file mode 100644 index 24d7ca6..0000000 --- a/C/695*_MaxAreaofIsland.c +++ /dev/null @@ -1,32 +0,0 @@ - -#define max(a, b) ((a > b) ? a : b) - -void traverse(int **grid, int i, int j, int n, int m, int *ret) -{ - - if (i < 0 || j < 0 || i > n - 1 || j > m - 1 || grid[i][j] == 0) - return; - grid[i][j] = 0; - *ret += 1; - traverse(grid, i - 1, j, n, m, ret); - traverse(grid, i, j - 1, n, m, ret); - traverse(grid, i + 1, j, n, m, ret); - traverse(grid, i, j + 1, n, m, ret); -} -int maxAreaOfIsland(int **grid, int gridSize, int *gridColSize) -{ - int ret = 0; - for (int i = 0; i < gridSize; ++i) - { - for (int j = 0; j < *(gridColSize + i); j++) - { - if (grid[i][j] == 1) - { - int area = 0; - traverse(grid, i, j, gridSize, *gridColSize, &area); - ret = max(ret, area); - } - } - } - return ret; -} \ No newline at end of file diff --git a/C/704*_BinarySearch.c b/C/704*_BinarySearch.c deleted file mode 100644 index d06ee34..0000000 --- a/C/704*_BinarySearch.c +++ /dev/null @@ -1,41 +0,0 @@ - - -int search(int *nums, int numsSize, int target) -{ - // normal version - // int l = 0, r = numsSize-1; - // while(l<=r){ - // int mid = l + (r-l)/2; - // if(nums[mid ] == target) return mid; - // else if(nums[mid] < target) l = mid+1; - // else r = mid-1; - // } - // return -1; - - // 左閉右開 區間 - // int l =0, r = numsSize; - // while(l numsSize-1) return -1; - // return nums[l]==target?l:-1; - - // left bound - int l = 0, r = numsSize; - while (l < r) - { - int mid = l + (r - l) / 2; - if (nums[mid] == target) - r = mid; - else if (nums[mid] < target) - l = mid + 1; - else - r = mid; - } - if (l > numsSize - 1) - return -1; - return nums[l] == target ? l : -1; -} diff --git a/C/733_FloodFill.c b/C/733_FloodFill.c deleted file mode 100644 index 9384a17..0000000 --- a/C/733_FloodFill.c +++ /dev/null @@ -1,39 +0,0 @@ - - -/** - * Return an array of arrays of size *returnSize. - * The sizes of the arrays are returned as *returnColumnSizes array. - * Note: Both returned array and *columnSizes array must be malloced, assume caller calls free(). - */ - -void fill(int **image, int imageSize, int imageColSize, int i, int j, int newColor, int oldColor) -{ - - if (i < 0 || i > imageSize - 1 || j < 0 || j > imageColSize - 1 || image[i][j] != oldColor) - return; - - image[i][j] = newColor; - fill(image, imageSize, imageColSize, i - 1, j, newColor, oldColor); - fill(image, imageSize, imageColSize, i, j - 1, newColor, oldColor); - fill(image, imageSize, imageColSize, i, j + 1, newColor, oldColor); - fill(image, imageSize, imageColSize, i + 1, j, newColor, oldColor); -} -int **floodFill(int **image, int imageSize, int *imageColSize, int sr, int sc, int newColor, int *returnSize, int **returnColumnSizes) -{ - // 1 1 1 - // 1 1 0 - // 1 0 1 - - *returnSize = imageSize; - int oldColor = image[sr][sc]; - *returnColumnSizes = malloc(sizeof(int) * imageSize); - for (int i = 0; i < imageSize; ++i) - { - (*returnColumnSizes)[i] = imageColSize[i]; - } - if (image[sr][sc] == newColor) - return image; - - fill(image, imageSize, *imageColSize, sr, sc, newColor, oldColor); - return image; -} \ No newline at end of file diff --git a/C/762*_PrimeNumberofSetBitsinBinaryRepresentation.c b/C/762*_PrimeNumberofSetBitsinBinaryRepresentation.c deleted file mode 100644 index 8b6b34f..0000000 --- a/C/762*_PrimeNumberofSetBitsinBinaryRepresentation.c +++ /dev/null @@ -1,34 +0,0 @@ - -int count(int n) -{ - // count the number of one - int ret = 0; - while (n) - { - ret++; - n &= n - 1; - } - return ret; -} -bool isPrime(int n) -{ - int primes[] = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29}; - for (int i = 0; i < 10; ++i) - { - if (n == primes[i]) - return true; - } - return false; -} -int countPrimeSetBits(int left, int right) -{ - int ret = 0; - - for (int i = left; i <= right; ++i) - { - int p = count(i); - if (isPrime(p)) - ret++; - } - return ret; -} \ No newline at end of file diff --git a/C/868_BinaryGap.c b/C/868_BinaryGap.c deleted file mode 100644 index 0eb58eb..0000000 --- a/C/868_BinaryGap.c +++ /dev/null @@ -1,23 +0,0 @@ -#define max(a, b) ((a > b) ? a : b) - -int binaryGap(int n) -{ - int ret = 0, pre = 0; - int i = 31; - while ((n >> i) != 1) - i--; - pre = i; - i--; - while (i > -1) - { - if ((n >> i) & 1) - { - ret = max(ret, pre - i); - pre = i; - } - i--; - } - return ret; - - -} \ No newline at end of file diff --git a/C/89_GrayCode.c b/C/89_GrayCode.c deleted file mode 100644 index 0e0f372..0000000 --- a/C/89_GrayCode.c +++ /dev/null @@ -1,39 +0,0 @@ - - -/** - * Note: The returned array must be malloced, assume caller calls free(). - */ -// int pow(int a, int n){ -// if(n==1) return a; -// return a*pow(n-1,a); -// } -int* grayCode(int n, int* returnSize){ - // n = 1, 00, 01 - // n = 2, 00, 01, 11, 10 - // n = 3, 000, 001, 011, 010, 110, 111, 101, 100 - // 後半段為前半段的最高位加一 - - *returnSize = pow(2,n); - int *ret = calloc(*returnSize, sizeof(int)); - ret[0] = 0, ret[1] = 1; - for(int i=2;i<=n;++i){ - int k = 1; - for(int j=pow(2,i-1) ;j< pow(2,i); ++j){ - ret[j] = ret[j - k] | (1<<(i-1)) ; - k+=2; - } - } - return ret; - - // option 2 bit manipulation - // n = 1, 00 01 - // n = 2, 00(00) 01(00) 11(10) 10(10) - // n = 3, 000, 001, 011, 010, 110, 111, 101, 100 - *returnSize = pow(2,n); - int *ret = calloc(*returnSize, sizeof(int)); - for(int i=0;i<(1<>1); - } - return ret; - -} \ No newline at end of file diff --git a/C/917_ReverseOnlyLetters.c b/C/917_ReverseOnlyLetters.c deleted file mode 100644 index 4010771..0000000 --- a/C/917_ReverseOnlyLetters.c +++ /dev/null @@ -1,35 +0,0 @@ - -void swap(char *a, char *b) -{ - char temp = *a; - *a = *b; - *b = temp; -} -bool isAlpha(char *c) -{ - if (*c - 'a' >= 0 && *c - 'a' < 26) - return true; - if (*c - 'A' >= 0 && *c - 'A' < 26) - return true; - return false; -} -char *reverseOnlyLetters(char *s) -{ - - int l = 0, r = strlen(s) - 1; - while (l < r) - { - - while (l < r && !isAlpha(&s[l])) - l++; - while (l < r && !isAlpha(&s[r])) - r--; - if (isAlpha(&s[l]) && isAlpha(&s[r])) - { - swap(&s[l], &s[r]); - l++; - r--; - } - } - return s; -} \ No newline at end of file diff --git a/C/978_LongestTurbulentSubarray.c b/C/978_LongestTurbulentSubarray.c deleted file mode 100644 index ecd6762..0000000 --- a/C/978_LongestTurbulentSubarray.c +++ /dev/null @@ -1,36 +0,0 @@ -#define max(a,b) ((a>b)?a:b) - -int maxTurbulenceSize(int* arr, int arrSize){ - - //r1 arr[0] < arr[1] arr[1] > arr[2] - //r2 arr[0] > arr[1] arr[1] < arr[2] - // two dp - // 9 4 2 10 7 8 8 1 9 - //r1 1 1 2 3 4 5 1 1 1 - //r2 1 2 1 1 1 1 1 2 3 - - int *r1 = calloc(arrSize, sizeof(int)), *r2 = calloc(arrSize, sizeof(int)); - r1[0] = 1, r2[0] = 1; - int ret = 1; - for(int i=1;i arr[i-1]) r2[i] = 1+ r2[i-1]; - else r2[i] = 1; - } - else{ - if(arr[i] > arr[i-1]) r1[i] = 1+ r1[i-1]; - else r1[i] = 1; - - if(arr[i] < arr[i-1]) r2[i] = 1+ r2[i-1]; - else r2[i] = 1; - } - ret = max(r1[i], ret); - ret = max(r2[i], ret); - printf("%d\t%d\n", r1[i],r2[i]); - } - return ret; - -} \ No newline at end of file diff --git a/C/Array/167_TwoSumII-InputArrayIsSorted.c b/C/Array/167_TwoSumII-InputArrayIsSorted.c new file mode 100644 index 0000000..3ac7a36 --- /dev/null +++ b/C/Array/167_TwoSumII-InputArrayIsSorted.c @@ -0,0 +1,30 @@ + + +/** + * Note: The returned array must be malloced, assume caller calls free(). + */ +int *twoSum(int *numbers, int numbersSize, int target, int *returnSize) +{ + int *ret = calloc(2, sizeof(int)); + *returnSize = 2; + for (int i = 0; i < numbersSize - 1; ++i) + { + int sum = target - numbers[i]; + int l = i + 1, r = numbersSize - 1; + while (l <= r) + { + int ≈ = l + (r - l) / 2; + if (sum == numbers[mid]) + { + ret[0] = i + 1; + ret[1] = mid + 1; + return ret; + } + else if (sum < numbers[mid]) + r = mid - 1; + else + l = mid + 1; + } + } + return ret; +} \ No newline at end of file diff --git a/C/Array/1_TwoSum.c b/C/Array/1_TwoSum.c new file mode 100644 index 0000000..1339d92 --- /dev/null +++ b/C/Array/1_TwoSum.c @@ -0,0 +1,24 @@ + + +/** + * Note: The returned array must be malloced, assume caller calls free(). + */ +int *twoSum(int *nums, int numsSize, int target, int *returnSize) +{ + int *ret = malloc(2 * sizeof(int)); + *returnSize = 2; + for (int i = 0; i < numsSize - 1; ++i) + { + int eval = target - nums[i]; + for (int j = i + 1; j < numsSize; ++j) + { + if (eval == nums[j]) + { + ret[0] = i; + ret[1] = j; + return ret; + } + } + } + return ret; +} \ No newline at end of file diff --git a/C/203_RemoveLinkedListElements.c b/C/Array/203_RemoveLinkedListElements.c similarity index 68% rename from C/203_RemoveLinkedListElements.c rename to C/Array/203_RemoveLinkedListElements.c index 064a8e4..60d4043 100644 --- a/C/203_RemoveLinkedListElements.c +++ b/C/Array/203_RemoveLinkedListElements.c @@ -10,8 +10,10 @@ struct ListNode *removeElements(struct ListNode *head, int val) { if (!head) return NULL; - struct ListNode *slow = malloc(sizeof(struct ListNode)), *fast = head, *ans = slow; - slow->next = head; + struct ListNode *ret = (struct ListNode *)malloc(sizeof(struct ListNode)); + ret->next = head; + ret->val = -1; + struct ListNode *slow = ret, *fast = head; while (fast) { if (fast->val != val) @@ -22,5 +24,5 @@ struct ListNode *removeElements(struct ListNode *head, int val) fast = fast->next; } slow->next = NULL; - return ans->next; + return ret->next; } \ No newline at end of file diff --git a/C/Array/26_RemoveDuplicatesfromSortedArray.c b/C/Array/26_RemoveDuplicatesfromSortedArray.c new file mode 100644 index 0000000..3b4113a --- /dev/null +++ b/C/Array/26_RemoveDuplicatesfromSortedArray.c @@ -0,0 +1,15 @@ + + +int removeDuplicates(int *nums, int numsSize) +{ + if (numsSize == 0) + return 0; + int slow = 0, fast = 0; + while (fast < numsSize) + { + if (nums[fast] != nums[slow]) + nums[++slow] = nums[fast]; + fast++; + } + return slow + 1; +} \ No newline at end of file diff --git a/C/27_RemoveElement.c b/C/Array/27_RemoveElement.c similarity index 64% rename from C/27_RemoveElement.c rename to C/Array/27_RemoveElement.c index daa2434..7048e58 100644 --- a/C/27_RemoveElement.c +++ b/C/Array/27_RemoveElement.c @@ -2,14 +2,14 @@ int removeElement(int *nums, int numsSize, int val) { - int slow = -1, fast = 0; + int slow = 0, fast = 0; while (fast < numsSize) { if (nums[fast] != val) { - nums[++slow] = nums[fast]; + nums[slow++] = nums[fast]; } fast++; } - return slow + 1; + return slow; } \ No newline at end of file diff --git a/C/283_MoveZeroes.c b/C/Array/283_MoveZeroes.c similarity index 71% rename from C/283_MoveZeroes.c rename to C/Array/283_MoveZeroes.c index d71b789..3fd2937 100644 --- a/C/283_MoveZeroes.c +++ b/C/Array/283_MoveZeroes.c @@ -2,17 +2,15 @@ void moveZeroes(int *nums, int numsSize) { - - int slow = -1, fast = 0; + int slow = 0, fast = 0; while (fast < numsSize) { if (nums[fast] != 0) { - nums[++slow] = nums[fast]; + nums[slow++] = nums[fast]; } fast++; } - slow++; while (slow < numsSize) nums[slow++] = 0; } \ No newline at end of file diff --git a/C/Array/344_ReverseString.c b/C/Array/344_ReverseString.c new file mode 100644 index 0000000..8d32080 --- /dev/null +++ b/C/Array/344_ReverseString.c @@ -0,0 +1,15 @@ + +void swap(char *a, char *b) +{ + char temp = *a; + *a = *b; + *b = temp; +} +void reverseString(char *s, int sSize) +{ + int l = 0, r = sSize - 1; + while (l < r) + { + swap(&s[l++], &s[r--]); + } +} \ No newline at end of file diff --git a/C/Array/345_ReverseVowelsofaString.c b/C/Array/345_ReverseVowelsofaString.c new file mode 100644 index 0000000..6848317 --- /dev/null +++ b/C/Array/345_ReverseVowelsofaString.c @@ -0,0 +1,36 @@ + +void swap(char *a, char *b) +{ + char temp = *a; + *a = *b; + *b = temp; +} +bool isVowel(char c) +{ + if ((c == 'A' || c == 'a') || + (c == 'E' || c == 'e') || + (c == 'I' || c == 'i') || + (c == 'O' || c == 'o') || + (c == 'U' || c == 'u')) + return true; + + return false; +} + +char *reverseVowels(char *s) +{ + int l = 0, r = 0; + for (int i = 0; s[i] != '\0'; ++i) + r++; + r--; + + while (l < r) + { + while (l < r && !isVowel(s[l])) + l++; + while (l < r && !isVowel(s[r])) + r--; + swap(&s[l++], &s[r--]); + } + return s; +} \ No newline at end of file diff --git a/C/Array/349_IntersectionofTwoArrays.c b/C/Array/349_IntersectionofTwoArrays.c new file mode 100644 index 0000000..1c6c5dc --- /dev/null +++ b/C/Array/349_IntersectionofTwoArrays.c @@ -0,0 +1,62 @@ + + +/** + * Note: The returned array must be malloced, assume caller calls free(). + */ +void swap(int *a, int *b) +{ + int temp = *a; + *a = *b; + *b = temp; +} +int partition(int *nums, int l, int r) +{ + int i = l - 1; + int pivot = nums[r]; + + for (int j = l; j <= r; ++j) + { + if (nums[j] < pivot) + swap(&nums[++i], &nums[j]); + } + swap(&nums[++i], &nums[r]); + return i; +} +void quickSort(int *nums, int l, int r) +{ + if (l < r) + { + int p = partition(nums, l, r); + quickSort(nums, l, p - 1); + quickSort(nums, p + 1, r); + } +} +int *intersection(int *nums1, int nums1Size, int *nums2, int nums2Size, int *returnSize) +{ + quickSort(nums1, 0, nums1Size - 1); + quickSort(nums2, 0, nums2Size - 1); + + int *ret = malloc(sizeof(int)); + int a = 0, b = 0, count = 1; + while (a < nums1Size && b < nums2Size) + { + if (nums1[a] == nums2[b]) + { + ret = realloc(ret, sizeof(int) * count); + ret[count - 1] = nums1[a]; + count++; + while (a < nums1Size - 1 && nums1[a] == nums1[a + 1]) + a++; + while (b < nums2Size - 1 && nums2[b] == nums2[b + 1]) + b++; + a++; + b++; + } + else if (nums1[a] < nums2[b]) + a++; + else + b++; + } + *returnSize = count - 1; + return ret; +} \ No newline at end of file diff --git a/C/Array/350_IntersectionofTwoArraysII.c b/C/Array/350_IntersectionofTwoArraysII.c new file mode 100644 index 0000000..5cadee0 --- /dev/null +++ b/C/Array/350_IntersectionofTwoArraysII.c @@ -0,0 +1,58 @@ + + +/** + * Note: The returned array must be malloced, assume caller calls free(). + */ + +void swap(int *a, int *b) +{ + int temp = *a; + *a = *b; + *b = temp; +} +int partition(int *nums, int l, int r) +{ + int pivot = nums[r]; + int i = l - 1; + for (int j = l; j <= r; ++j) + { + if (nums[j] < pivot) + swap(&nums[++i], &nums[j]); + } + i++; + swap(&nums[r], &nums[i]); + return i; +} +void quickSort(int *nums, int l, int r) +{ + if (l < r) + { + int p = partition(nums, l, r); + quickSort(nums, l, p - 1); + quickSort(nums, p + 1, r); + } +} +int *intersect(int *nums1, int nums1Size, int *nums2, int nums2Size, int *returnSize) +{ + quickSort(nums1, 0, nums1Size - 1); + quickSort(nums2, 0, nums2Size - 1); + int a = 0, b = 0, count = 1; + int *ret = malloc(sizeof(int)); + while (a < nums1Size && b < nums2Size) + { + if (nums1[a] == nums2[b]) + { + ret = realloc(ret, sizeof(int) * count); + ret[count - 1] = nums1[a]; + count++; + a++; + b++; + } + else if (nums1[a] < nums2[b]) + a++; + else + b++; + } + *returnSize = count - 1; + return ret; +} \ No newline at end of file diff --git a/C/541_ReverseStringII.c b/C/Array/541_ReverseStringII.c similarity index 96% rename from C/541_ReverseStringII.c rename to C/Array/541_ReverseStringII.c index 8846aa9..04c469c 100644 --- a/C/541_ReverseStringII.c +++ b/C/Array/541_ReverseStringII.c @@ -14,9 +14,11 @@ void reverse(char *s, int l, int r) } char *reverseStr(char *s, int k) { + if (k == 1) return s; int len = strlen(s); + int l = 0; for (int i = 0; i < len; i += 2 * k) { reverse(s, i, min(i + k - 1, len - 1)); diff --git a/C/Array/82_RemoveDuplicatesfromSortedListII.c b/C/Array/82_RemoveDuplicatesfromSortedListII.c new file mode 100644 index 0000000..3dc4fae --- /dev/null +++ b/C/Array/82_RemoveDuplicatesfromSortedListII.c @@ -0,0 +1,29 @@ +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * struct ListNode *next; + * }; + */ + +struct ListNode *deleteDuplicates(struct ListNode *head) +{ + if (!head) + return NULL; + struct ListNode *ret = (struct ListNode *)malloc(sizeof(struct ListNode)); + ret->val = -101; + ret->next = head; + struct ListNode *slow; + slow = ret; + while (slow->next) + { + struct ListNode *fast = slow->next; + while (fast->next && fast->val == fast->next->val) + fast = fast->next; + if (slow->next == fast) + slow = slow->next; + else + slow->next = fast->next; + } + return ret->next; +} \ No newline at end of file diff --git a/C/83_RemoveDuplicatesfromSortedList.c b/C/Array/83_RemoveDuplicatesfromSortedList.c similarity index 79% rename from C/83_RemoveDuplicatesfromSortedList.c rename to C/Array/83_RemoveDuplicatesfromSortedList.c index 7e4cc77..e118837 100644 --- a/C/83_RemoveDuplicatesfromSortedList.c +++ b/C/Array/83_RemoveDuplicatesfromSortedList.c @@ -8,9 +8,10 @@ struct ListNode *deleteDuplicates(struct ListNode *head) { - if (!head || !head->next) - return head; - struct ListNode *slow = head, *fast = head; + struct ListNode *slow, *fast; + if (!head) + return NULL; + slow = fast = head; while (fast) { if (fast->val != slow->val) diff --git a/C/Array/870_AdvantageShuffle.cpp b/C/Array/870_AdvantageShuffle.cpp new file mode 100644 index 0000000..ba93005 --- /dev/null +++ b/C/Array/870_AdvantageShuffle.cpp @@ -0,0 +1,29 @@ +class Solution +{ +public: + vector advantageCount(vector &nums1, vector &nums2) + { + priority_queue > pq; + int n = nums1.size(); + vector ret(n, 0); + for (int i = 0; i < nums2.size(); ++i) + pq.push(make_pair(nums2[i], i)); + sort(nums1.begin(), nums1.end()); + int l = 0, r = n - 1; + while (!pq.empty()) + { + pair p = pq.top(); + pq.pop(); + int maxVal = p.first, i = p.second; + if (maxVal >= nums1[r]) + { + ret[i] = nums1[l++]; + } + else + { + ret[i] = nums1[r--]; + } + } + return ret; + } +}; \ No newline at end of file diff --git a/C/Binary Search Tree/1038_BinarySearchTreetoGreaterSumTree.c b/C/Binary Search Tree/1038_BinarySearchTreetoGreaterSumTree.c new file mode 100644 index 0000000..fba9811 --- /dev/null +++ b/C/Binary Search Tree/1038_BinarySearchTreetoGreaterSumTree.c @@ -0,0 +1,24 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * struct TreeNode *left; + * struct TreeNode *right; + * }; + */ + +void traverse(struct TreeNode *root, int *sum) +{ + if (!root) + return NULL; + traverse(root->right, sum); + (*sum) += root->val; + root->val = *sum; + traverse(root->left, sum); +} +struct TreeNode *bstToGst(struct TreeNode *root) +{ + int sum = 0; + traverse(root, &sum); + return root; +} \ No newline at end of file diff --git a/C/Binary Search Tree/222_CountCompleteTreeNodes.c b/C/Binary Search Tree/222_CountCompleteTreeNodes.c new file mode 100644 index 0000000..6cace93 --- /dev/null +++ b/C/Binary Search Tree/222_CountCompleteTreeNodes.c @@ -0,0 +1,32 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * struct TreeNode *left; + * struct TreeNode *right; + * }; + */ + +int countNodes(struct TreeNode *root) +{ + if (!root) + return 0; + int count = 0; + struct TreeNode *left, *right; + left = right = root; + int l = 1, r = 1; + while (left->left) + { + left = left->left; + l++; + } + while (right->right) + { + right = right->right; + r++; + } + if (l == r) + return pow(2, l) - 1; + else + return 1 + countNodes(root->left) + countNodes(root->right); +} \ No newline at end of file diff --git a/C/230_KthSmallestElementinaBST.c b/C/Binary Search Tree/230_KthSmallestElementinaBST.c similarity index 83% rename from C/230_KthSmallestElementinaBST.c rename to C/Binary Search Tree/230_KthSmallestElementinaBST.c index 6dee381..153450d 100644 --- a/C/230_KthSmallestElementinaBST.c +++ b/C/Binary Search Tree/230_KthSmallestElementinaBST.c @@ -9,10 +9,11 @@ void traverse(struct TreeNode *root, int *k, int *ret) { - if (root == NULL) + + if (!root) return; traverse(root->left, k, ret); - *k -= 1; // + (*k)--; if (*k == 0) { *ret = root->val; @@ -22,8 +23,7 @@ void traverse(struct TreeNode *root, int *k, int *ret) } int kthSmallest(struct TreeNode *root, int k) { - int count = k; int ret = 0; - traverse(root, &count, &ret); + traverse(root, &k, &ret); return ret; } \ No newline at end of file diff --git a/C/Binary Search Tree/235_LowestCommonAncestorofaBinarySearchTree.c b/C/Binary Search Tree/235_LowestCommonAncestorofaBinarySearchTree.c new file mode 100644 index 0000000..5e28ffd --- /dev/null +++ b/C/Binary Search Tree/235_LowestCommonAncestorofaBinarySearchTree.c @@ -0,0 +1,23 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * struct TreeNode *left; + * struct TreeNode *right; + * }; + */ + +struct TreeNode *lowestCommonAncestor(struct TreeNode *root, struct TreeNode *p, struct TreeNode *q) +{ + if (!root) + return NULL; + if (root == p || root == q) + return root; + + if (root->val < p->val && root->val < q->val) + return lowestCommonAncestor(root->right, p, q); + else if (root->val > p->val && root->val > q->val) + return lowestCommonAncestor(root->left, p, q); + else + return root; +} \ No newline at end of file diff --git a/C/Binary Search Tree/236_LowestCommonAncestorofaBinaryTree.c b/C/Binary Search Tree/236_LowestCommonAncestorofaBinaryTree.c new file mode 100644 index 0000000..9f2e5cc --- /dev/null +++ b/C/Binary Search Tree/236_LowestCommonAncestorofaBinaryTree.c @@ -0,0 +1,24 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * struct TreeNode *left; + * struct TreeNode *right; + * }; + */ +struct TreeNode *lowestCommonAncestor(struct TreeNode *root, struct TreeNode *p, struct TreeNode *q) +{ + + if (!root) + return NULL; + if (root == p || root == q) + return root; + struct TreeNode *left = lowestCommonAncestor(root->left, p, q); + struct TreeNode *right = lowestCommonAncestor(root->right, p, q); + if (left && right) + return root; + else if (!left && !right) + return NULL; + else + return left ? left : right; +} \ No newline at end of file diff --git a/C/450_DeleteNodeinaBST.c b/C/Binary Search Tree/450_DeleteNodeinaBST.c similarity index 71% rename from C/450_DeleteNodeinaBST.c rename to C/Binary Search Tree/450_DeleteNodeinaBST.c index 4a48054..07bc0f8 100644 --- a/C/450_DeleteNodeinaBST.c +++ b/C/Binary Search Tree/450_DeleteNodeinaBST.c @@ -15,23 +15,21 @@ struct TreeNode *findNext(struct TreeNode *root) } struct TreeNode *deleteNode(struct TreeNode *root, int key) { - - if (root == NULL) + if (!root) return NULL; - if (root->val == key) + if (key == root->val) { if (!root->left) return root->right; if (!root->right) return root->left; - - struct TreeNode *p = findNext(root->right); - root->val = p->val; - root->right = deleteNode(root->right, p->val); + struct TreeNode *temp = findNext(root->right); + root->val = temp->val; + root->right = deleteNode(root->right, root->val); } - else if (root->val < key) - root->right = deleteNode(root->right, key); - else if (root->val > key) + else if (key < root->val) root->left = deleteNode(root->left, key); + else + root->right = deleteNode(root->right, key); return root; } \ No newline at end of file diff --git a/C/Binary Search Tree/538_ConvertBSTtoGreaterTree.c b/C/Binary Search Tree/538_ConvertBSTtoGreaterTree.c new file mode 100644 index 0000000..345e109 --- /dev/null +++ b/C/Binary Search Tree/538_ConvertBSTtoGreaterTree.c @@ -0,0 +1,25 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * struct TreeNode *left; + * struct TreeNode *right; + * }; + */ + +void traverse(struct TreeNode *root, int *sum) +{ + if (!root) + return NULL; + + traverse(root->right, sum); + (*sum) += root->val; + root->val = *sum; + traverse(root->left, sum); +} +struct TreeNode *convertBST(struct TreeNode *root) +{ + int sum = 0; + traverse(root, &sum); + return root; +} \ No newline at end of file diff --git a/C/700_SearchinaBinarySearchTree.c b/C/Binary Search Tree/700_SearchinaBinarySearchTree.c similarity index 77% rename from C/700_SearchinaBinarySearchTree.c rename to C/Binary Search Tree/700_SearchinaBinarySearchTree.c index cf6a651..7a9b131 100644 --- a/C/700_SearchinaBinarySearchTree.c +++ b/C/Binary Search Tree/700_SearchinaBinarySearchTree.c @@ -11,11 +11,10 @@ struct TreeNode *searchBST(struct TreeNode *root, int val) { if (!root) return NULL; - if (root->val == val) + if (val == root->val) return root; - else if (root->val < val) - return searchBST(root->right, val); - else if (root->val > val) + else if (val < root->val) return searchBST(root->left, val); - return NULL; + else + return searchBST(root->right, val); } \ No newline at end of file diff --git a/C/701_InsertintoaBinarySearchTree.c b/C/Binary Search Tree/701_InsertintoaBinarySearchTree.c similarity index 94% rename from C/701_InsertintoaBinarySearchTree.c rename to C/Binary Search Tree/701_InsertintoaBinarySearchTree.c index 059c416..6ab9a55 100644 --- a/C/701_InsertintoaBinarySearchTree.c +++ b/C/Binary Search Tree/701_InsertintoaBinarySearchTree.c @@ -9,7 +9,6 @@ struct TreeNode *insertIntoBST(struct TreeNode *root, int val) { - if (!root) { struct TreeNode *ret = (struct TreeNode *)malloc(sizeof(struct TreeNode)); @@ -20,7 +19,7 @@ struct TreeNode *insertIntoBST(struct TreeNode *root, int val) } if (root->val < val) root->right = insertIntoBST(root->right, val); - else if (root->val > val) + else root->left = insertIntoBST(root->left, val); return root; } \ No newline at end of file diff --git a/C/Binary Search Tree/96_UniqueBinarySearchTrees.c b/C/Binary Search Tree/96_UniqueBinarySearchTrees.c new file mode 100644 index 0000000..b098f3f --- /dev/null +++ b/C/Binary Search Tree/96_UniqueBinarySearchTrees.c @@ -0,0 +1,22 @@ + + +int numTrees(int n) +{ + int *dp = calloc(n + 1, sizeof(int)); + // n=1, 1 + // n=2, 2 + // n =3, 5 = 1*2 + 2*1 + //n=4 , 14 = 5*2 + // n =5 , 42 + // dp + // 1, 1, dp[0]*dp[1]+dp[1]*dp[0], dp[0]*dp[2]+dp[1]*dp[1]+dp[2]*dp[0] + dp[0] = 1, dp[1] = 1; + for (int i = 2; i <= n; ++i) + { + for (int j = 0; j < i; ++j) + { + dp[i] += dp[j] * dp[i - 1 - j]; + } + } + return dp[n]; +} \ No newline at end of file diff --git a/C/98_ValidateBinarySearchTree.c b/C/Binary Search Tree/98_ValidateBinarySearchTree.c similarity index 55% rename from C/98_ValidateBinarySearchTree.c rename to C/Binary Search Tree/98_ValidateBinarySearchTree.c index 70306db..3c8501e 100644 --- a/C/98_ValidateBinarySearchTree.c +++ b/C/Binary Search Tree/98_ValidateBinarySearchTree.c @@ -7,20 +7,16 @@ * }; */ -bool isValid(struct TreeNode *root, long l, long r) +bool isValid(struct TreeNode *root, long mn, long mx) { - if (!root) return true; - if (l >= root->val) - return false; - if (r <= root->val) + if (root->val <= mn || root->val >= mx) return false; - return isValid(root->left, l, root->val) && isValid(root->right, root->val, r); + return isValid(root->left, mn, root->val) && isValid(root->right, root->val, mx); } bool isValidBST(struct TreeNode *root) { - if (!root) - return true; + return isValid(root, LONG_MIN, LONG_MAX); } \ No newline at end of file diff --git a/C/BinarySearch/1011_CapacityToShipPackagesWithinDDays.c b/C/BinarySearch/1011_CapacityToShipPackagesWithinDDays.c new file mode 100644 index 0000000..2e22d81 --- /dev/null +++ b/C/BinarySearch/1011_CapacityToShipPackagesWithinDDays.c @@ -0,0 +1,39 @@ +#define max(a, b) ((a > b) ? a : b) +int costDays(int *weights, int weightsSize, int cap) +{ + + int days = 0; + for (int i = 0; i < weightsSize;) + { + + int c = cap; + while (i < weightsSize && c >= weights[i]) + { + c -= weights[i]; + ++i; + } + days++; + } + + return days; +} +int shipWithinDays(int *weights, int weightsSize, int days) +{ + int l = 0, r = INT_MAX; + for (int i = 0; i < weightsSize; ++i) + { + l = max(l, weights[i]); + } + while (l < r) + { + int mid = l + (r - l) / 2; + int evalDay = costDays(weights, weightsSize, mid); + if (evalDay == days) + r = mid; + else if (evalDay < days) + r = mid; + else + l = mid + 1; + } + return l; +} \ No newline at end of file diff --git a/C/BinarySearch/278_FirstBadVersion.c b/C/BinarySearch/278_FirstBadVersion.c new file mode 100644 index 0000000..598953a --- /dev/null +++ b/C/BinarySearch/278_FirstBadVersion.c @@ -0,0 +1,17 @@ +// The API isBadVersion is defined for you. +// bool isBadVersion(int version); + +int firstBadVersion(int n) +{ + + int l = 1, r = n; + while (l <= r) + { + int mid = l + (r - l) / 2; + if (isBadVersion(mid)) + r = mid - 1; + else + l = mid + 1; + } + return l; +} \ No newline at end of file diff --git a/C/BinarySearch/34_FindFirstandLastPositionofElementinSortedArray.c b/C/BinarySearch/34_FindFirstandLastPositionofElementinSortedArray.c new file mode 100644 index 0000000..0959f15 --- /dev/null +++ b/C/BinarySearch/34_FindFirstandLastPositionofElementinSortedArray.c @@ -0,0 +1,34 @@ + + +/** + * Note: The returned array must be malloced, assume caller calls free(). + */ +int *searchRange(int *nums, int numsSize, int target, int *returnSize) +{ + // 先用Binary Search 找到 陣列中有多少元素小於target(也就是說 target 要插入陣列需要插入在哪個位置) + + int l = 0, r = numsSize; + *returnSize = 2; + int *ret = calloc(*returnSize, sizeof(int)); + ret[0] = ret[1] = -1; + if (numsSize == 0) + return ret; + while (l < r) + { + int mid = l + (r - l) / 2; + if (nums[mid] == target) + r = mid; + else if (nums[mid] > target) + r = mid; + else + l = mid + 1; + } + if (l < 0 || l > numsSize - 1 || nums[l] != target) + return ret; + r = l; + while (r < numsSize - 1 && nums[r + 1] == nums[r]) + r++; + ret[0] = l; + ret[1] = r; + return ret; +} diff --git a/C/BinarySearch/35_SearchInsertPosition.c b/C/BinarySearch/35_SearchInsertPosition.c new file mode 100644 index 0000000..39dd446 --- /dev/null +++ b/C/BinarySearch/35_SearchInsertPosition.c @@ -0,0 +1,17 @@ + + +int searchInsert(int *nums, int numsSize, int target) +{ + int l = 0, r = numsSize; + while (l < r) + { + int mid = l + (r - l) / 2; + if (nums[mid] == target) + return mid; + else if (nums[mid] < target) + l = mid + 1; + else + r = mid; + } + return l; +} \ No newline at end of file diff --git a/C/BinarySearch/704_BinarySearch.c b/C/BinarySearch/704_BinarySearch.c new file mode 100644 index 0000000..b5246de --- /dev/null +++ b/C/BinarySearch/704_BinarySearch.c @@ -0,0 +1,28 @@ + + +int search(int *nums, int numsSize, int target) +{ + // int l = 0, r = numsSize-1; + // while(l<=r){ + // int mid = l+(r-l)/2; + // if(nums[mid] == target) return mid; + // else if(nums[mid]b)?a:b) + +int CostHour(int *piles, int pilesSize, int sp){ + int hours = 0; + for(int i=0;i pr || il > ir) + return NULL; + + struct TreeNode *root = (struct TreeNode *)malloc(sizeof(struct TreeNode)); + root->val = preorder[pl]; + int idx = -1; + for (int i = il; i <= ir; ++i) + { + if (inorder[i] == root->val) + { + idx = i; + break; + } + } + + root->left = construct(preorder, pl + 1, pl + idx - il, inorder, il, idx - 1); + root->right = construct(preorder, pl + idx - il + 1, pr, inorder, idx + 1, ir); + return root; +} +struct TreeNode *buildTree(int *preorder, int preorderSize, int *inorder, int inorderSize) +{ + return construct(preorder, 0, preorderSize - 1, inorder, 0, inorderSize - 1); +} \ No newline at end of file diff --git a/C/BinaryTree/106_ConstructBinaryTreefromInorderandPostorderTraversal.c b/C/BinaryTree/106_ConstructBinaryTreefromInorderandPostorderTraversal.c new file mode 100644 index 0000000..e2d2200 --- /dev/null +++ b/C/BinaryTree/106_ConstructBinaryTreefromInorderandPostorderTraversal.c @@ -0,0 +1,34 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * struct TreeNode *left; + * struct TreeNode *right; + * }; + */ + +struct TreeNode *construct(int *inorder, int il, int ir, int *postorder, int pl, int pr) +{ + + if (il > ir || pl > pr) + return NULL; + + int idx = -1; + struct TreeNode *root = (struct TreeNode *)malloc(sizeof(struct TreeNode)); + root->val = postorder[pr]; + for (int i = il; i <= ir; ++i) + { + if (root->val == inorder[i]) + { + idx = i; + break; + } + } + root->left = construct(inorder, il, idx - 1, postorder, pl, pl + idx - il - 1); + root->right = construct(inorder, idx + 1, ir, postorder, pl + idx - il, pr - 1); + return root; +} +struct TreeNode *buildTree(int *inorder, int inorderSize, int *postorder, int postorderSize) +{ + return construct(inorder, 0, inorderSize - 1, postorder, 0, postorderSize - 1); +} diff --git a/C/114_FlattenBinaryTreetoLinkedList.c b/C/BinaryTree/114_FlattenBinaryTreetoLinkedList.c similarity index 91% rename from C/114_FlattenBinaryTreetoLinkedList.c rename to C/BinaryTree/114_FlattenBinaryTreetoLinkedList.c index f25943b..36e50fa 100644 --- a/C/114_FlattenBinaryTreetoLinkedList.c +++ b/C/BinaryTree/114_FlattenBinaryTreetoLinkedList.c @@ -13,10 +13,10 @@ void flatten(struct TreeNode *root) return; flatten(root->left); flatten(root->right); - struct TreeNde *temp = root->right; + struct TreeNode *temp = root->right; + struct TreeNode *p = root; root->right = root->left; root->left = NULL; - struct TreeNode *p = root; while (p->right) p = p->right; p->right = temp; diff --git a/C/116_PopulatingNextRightPointersinEachNode.c b/C/BinaryTree/116_PopulatingNextRightPointersinEachNode.c similarity index 67% rename from C/116_PopulatingNextRightPointersinEachNode.c rename to C/BinaryTree/116_PopulatingNextRightPointersinEachNode.c index 6419b1f..55ea8f9 100644 --- a/C/116_PopulatingNextRightPointersinEachNode.c +++ b/C/BinaryTree/116_PopulatingNextRightPointersinEachNode.c @@ -8,18 +8,21 @@ * }; */ +void connection(struct Node *left, struct Node *right) +{ + + if (!left || !right) + return; -void connection(struct Node *left, struct Node *right){ - - if(!right || !left) return; - left->next = right; connection(left->left, left->right); connection(right->left, right->right); connection(left->right, right->left); } -struct Node* connect(struct Node* root) { - if(!root) return root; +struct Node *connect(struct Node *root) +{ + if (!root) + return root; connection(root->left, root->right); return root; } \ No newline at end of file diff --git a/C/BinaryTree/226_InvertBinaryTree.c b/C/BinaryTree/226_InvertBinaryTree.c new file mode 100644 index 0000000..0d6be80 --- /dev/null +++ b/C/BinaryTree/226_InvertBinaryTree.c @@ -0,0 +1,20 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * struct TreeNode *left; + * struct TreeNode *right; + * }; + */ + +struct TreeNode *invertTree(struct TreeNode *root) +{ + if (!root) + return root; + root->left = invertTree(root->left); + root->right = invertTree(root->right); + struct TreeNode *temp = root->left; + root->left = root->right; + root->right = temp; + return root; +} \ No newline at end of file diff --git a/C/BinaryTree/654_MaximumBinaryTree.c b/C/BinaryTree/654_MaximumBinaryTree.c new file mode 100644 index 0000000..762506e --- /dev/null +++ b/C/BinaryTree/654_MaximumBinaryTree.c @@ -0,0 +1,33 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * struct TreeNode *left; + * struct TreeNode *right; + * }; + */ + +struct TreeNode *construct(int *nums, int l, int r) +{ + if (l > r) + return NULL; + int idx = l, val = nums[l]; + for (int i = l; i <= r; ++i) + { + if (val < nums[i]) + { + val = nums[i]; + idx = i; + } + } + + struct TreeNode *root = (struct TreeNode *)malloc(sizeof(struct TreeNode)); + root->val = val; + root->left = construct(nums, l, idx - 1); + root->right = construct(nums, idx + 1, r); + return root; +} +struct TreeNode *constructMaximumBinaryTree(int *nums, int numsSize) +{ + return construct(nums, 0, numsSize - 1); +} \ No newline at end of file diff --git a/C/BitManipulation/1342_NumberofStepstoReduceaNumbertoZero.c b/C/BitManipulation/1342_NumberofStepstoReduceaNumbertoZero.c new file mode 100644 index 0000000..8328891 --- /dev/null +++ b/C/BitManipulation/1342_NumberofStepstoReduceaNumbertoZero.c @@ -0,0 +1,19 @@ + + +int numberOfSteps(int num) +{ + // if(num==0) return 0; + // if((num&1)==0) return 1+numberOfSteps(num/2); + // else return 1+numberOfSteps(num-1); + + int ret = 0; + while (num) + { + if (num % 2 == 0) + num >>= 1; + else + num--; + ret++; + } + return ret; +} \ No newline at end of file diff --git a/C/136_SingleNumber.c b/C/BitManipulation/136_SingleNumber.c similarity index 77% rename from C/136_SingleNumber.c rename to C/BitManipulation/136_SingleNumber.c index 6c5150a..419cbdd 100644 --- a/C/136_SingleNumber.c +++ b/C/BitManipulation/136_SingleNumber.c @@ -1,10 +1,9 @@ + + int singleNumber(int *nums, int numsSize) { int ret = 0; for (int i = 0; i < numsSize; ++i) - { - // ret ^= *(nums+i); ret ^= nums[i]; - } return ret; } \ No newline at end of file diff --git a/C/137*_SingleNumberII.c b/C/BitManipulation/137_SingleNumberII.c similarity index 78% rename from C/137*_SingleNumberII.c rename to C/BitManipulation/137_SingleNumberII.c index 3c2b37f..3256eab 100644 --- a/C/137*_SingleNumberII.c +++ b/C/BitManipulation/137_SingleNumberII.c @@ -2,8 +2,7 @@ int singleNumber(int *nums, int numsSize) { - - long ret = 0; + int ret = 0; for (int i = 0; i < 32; ++i) { long sum = 0; @@ -11,7 +10,8 @@ int singleNumber(int *nums, int numsSize) { sum += (nums[j] >> i) & 1; } - ret += (sum % 3) << i; + sum %= 3; + ret += (sum) << i; } return ret; } \ No newline at end of file diff --git a/C/BitManipulation/1486_XOROperationinanArray.c b/C/BitManipulation/1486_XOROperationinanArray.c new file mode 100644 index 0000000..2f5bb35 --- /dev/null +++ b/C/BitManipulation/1486_XOROperationinanArray.c @@ -0,0 +1,11 @@ + + +int xorOperation(int n, int start) +{ + int ret = 0; + for (int i = 0; i < n; ++i) + { + ret ^= start + 2 * i; + } + return ret; +} \ No newline at end of file diff --git a/C/1720_DecodeXORedArray.c b/C/BitManipulation/1720_DecodeXORedArray.c similarity index 57% rename from C/1720_DecodeXORedArray.c rename to C/BitManipulation/1720_DecodeXORedArray.c index 73f0e5c..7c451a3 100644 --- a/C/1720_DecodeXORedArray.c +++ b/C/BitManipulation/1720_DecodeXORedArray.c @@ -5,22 +5,14 @@ */ int *decode(int *encoded, int encodedSize, int first, int *returnSize) { - *returnSize = encodedSize + 1; int *ret = calloc(*returnSize, sizeof(int)); int pre = first; - // 1 0 2 1 => 1 2 3 - // xor 交換律 - // 2^1 = 3 then 1 = 3^2, - // 0^2 = 2 then 0 = 2^2, - // 1^0 = 1 then 1 = 1^0, - // first = 1 - // first^en[i] = arr[i+1] , first = arr[i+1] ret[0] = first; for (int i = 1; i < *returnSize; ++i) { - ret[i] = first ^ encoded[i - 1]; - first = ret[i]; + ret[i] = encoded[i - 1] ^ pre; + pre = ret[i]; } return ret; } \ No newline at end of file diff --git a/C/190_Reverse Bits.c b/C/BitManipulation/190_ReverseBits.c similarity index 91% rename from C/190_Reverse Bits.c rename to C/BitManipulation/190_ReverseBits.c index 3687194..152bc87 100644 --- a/C/190_Reverse Bits.c +++ b/C/BitManipulation/190_ReverseBits.c @@ -1,6 +1,6 @@ uint32_t reverseBits(uint32_t n) { - // option 1 + uint32_t ret = 0; for (int i = 0; i < 32; ++i) { diff --git a/C/191_Numberof1Bits.c b/C/BitManipulation/191_Numberof1Bits.c similarity index 60% rename from C/191_Numberof1Bits.c rename to C/BitManipulation/191_Numberof1Bits.c index ea64b84..d29ff2f 100644 --- a/C/191_Numberof1Bits.c +++ b/C/BitManipulation/191_Numberof1Bits.c @@ -1,10 +1,10 @@ int hammingWeight(uint32_t n) { - int count = 0; + int ret = 0; while (n) { - count++; n = n & (n - 1); + ret++; } - return count; + return ret; } \ No newline at end of file diff --git a/C/201_BitwiseANDofNumbersRange.c b/C/BitManipulation/201_BitwiseANDofNumbersRange.c similarity index 66% rename from C/201_BitwiseANDofNumbersRange.c rename to C/BitManipulation/201_BitwiseANDofNumbersRange.c index 1aff47f..e4bfd14 100644 --- a/C/201_BitwiseANDofNumbersRange.c +++ b/C/BitManipulation/201_BitwiseANDofNumbersRange.c @@ -2,13 +2,12 @@ int rangeBitwiseAnd(int left, int right) { - int i = 0; - + int count = 0; while (left != right) { - i++; left >>= 1; right >>= 1; + count++; } - return right << i; + return right << count; } \ No newline at end of file diff --git a/C/BitManipulation/2119_ANumberAfteraDoubleReversal.c b/C/BitManipulation/2119_ANumberAfteraDoubleReversal.c new file mode 100644 index 0000000..cbce47b --- /dev/null +++ b/C/BitManipulation/2119_ANumberAfteraDoubleReversal.c @@ -0,0 +1,18 @@ + +int reverse(int x) +{ + int rever = 0; + int num = x; + while (x > 0) + { + rever = rever * 10 + (x % 10); + x /= 10; + } + return rever; +} +bool isSameAfterReversals(int num) +{ + if (num == 0) + return true; + return num == reverse(reverse(num)); +} \ No newline at end of file diff --git a/C/231_PowerofTwo.c b/C/BitManipulation/231_PowerofTwo.c similarity index 97% rename from C/231_PowerofTwo.c rename to C/BitManipulation/231_PowerofTwo.c index a735050..7571de4 100644 --- a/C/231_PowerofTwo.c +++ b/C/BitManipulation/231_PowerofTwo.c @@ -1,3 +1,5 @@ + + bool isPowerOfTwo(int n) { if (n <= 0) diff --git a/C/260*_SingleNumberIII.cpp b/C/BitManipulation/260_SingleNumberIII.c similarity index 73% rename from C/260*_SingleNumberIII.cpp rename to C/BitManipulation/260_SingleNumberIII.c index 9d37ad7..e417aa2 100644 --- a/C/260*_SingleNumberIII.cpp +++ b/C/BitManipulation/260_SingleNumberIII.c @@ -5,18 +5,18 @@ */ int *singleNumber(int *nums, int numsSize, int *returnSize) { - long diff = 0; + *returnSize = 2; + int *ret = calloc(*returnSize, sizeof(int)); + unsigned int diff = 0; for (int i = 0; i < numsSize; ++i) - diff ^= *(nums + i); + diff ^= nums[i]; diff &= -diff; - *returnSize = 2; - int *ret = calloc(2, sizeof(int)); for (int i = 0; i < numsSize; ++i) { - if (nums[i] & diff) + if (diff & nums[i]) ret[0] ^= nums[i]; else ret[1] ^= nums[i]; } return ret; -} \ No newline at end of file +} diff --git a/C/BitManipulation/268_MissingNumber.c b/C/BitManipulation/268_MissingNumber.c new file mode 100644 index 0000000..e7203b5 --- /dev/null +++ b/C/BitManipulation/268_MissingNumber.c @@ -0,0 +1,11 @@ + + +int missingNumber(int *nums, int numsSize) +{ + int ret = numsSize; + for (int i = 0; i < numsSize; ++i) + { + ret ^= (i ^ nums[i]); + } + return ret; +} \ No newline at end of file diff --git a/C/BitManipulation/287_FindtheDuplicateNumber.c b/C/BitManipulation/287_FindtheDuplicateNumber.c new file mode 100644 index 0000000..0238b79 --- /dev/null +++ b/C/BitManipulation/287_FindtheDuplicateNumber.c @@ -0,0 +1,23 @@ + + +int findDuplicate(int *nums, int numsSize) +{ + int slow = 0, fast = 0; + + while (1) + { + slow = nums[slow]; + fast = nums[nums[fast]]; + if (slow == fast) + break; + } + fast = 0; + while (1) + { + slow = nums[slow]; + fast = nums[fast]; + if (fast == slow) + return slow; + } + return -1; +} \ No newline at end of file diff --git a/C/BitManipulation/326_PowerofThree.c b/C/BitManipulation/326_PowerofThree.c new file mode 100644 index 0000000..a3891e8 --- /dev/null +++ b/C/BitManipulation/326_PowerofThree.c @@ -0,0 +1,10 @@ + + +bool isPowerOfThree(int n) +{ + if (n <= 0) + return false; + while (n % 3 == 0) + n /= 3; + return n == 1; +} \ No newline at end of file diff --git a/C/BitManipulation/338_CountingBits.c b/C/BitManipulation/338_CountingBits.c new file mode 100644 index 0000000..92dbcbb --- /dev/null +++ b/C/BitManipulation/338_CountingBits.c @@ -0,0 +1,29 @@ + + +/** + * Note: The returned array must be malloced, assume caller calls free(). + */ + +int count(int n) +{ + int ret = 0; + while (n) + { + n = n & (n - 1); + ret++; + } + return ret; +} +int *countBits(int n, int *returnSize) +{ + *returnSize = n + 1; + int *ret = calloc(n + 1, sizeof(int)); + // for(int i=0;i<=n;++i){ + // ret[i] = count(i); + // } + for (int i = 1; i <= n; ++i) + { + ret[i] = ret[i & (i - 1)] + 1; + } + return ret; +} \ No newline at end of file diff --git a/C/BitManipulation/342_PowerofFour.c b/C/BitManipulation/342_PowerofFour.c new file mode 100644 index 0000000..7a809e0 --- /dev/null +++ b/C/BitManipulation/342_PowerofFour.c @@ -0,0 +1,14 @@ + + +bool isPowerOfFour(int n) +{ + // if(n<=0) return false; + // while(n%4==0) n/=4; + // return n==1; + + if (n <= 0) + return false; + if ((n & (n - 1)) != 0) + return false; + return (n & (0x55555555)) == n; +} \ No newline at end of file diff --git a/C/389_FindtheDifference.c b/C/BitManipulation/389_FindtheDifference.c similarity index 58% rename from C/389_FindtheDifference.c rename to C/BitManipulation/389_FindtheDifference.c index 7dc179b..07ddd03 100644 --- a/C/389_FindtheDifference.c +++ b/C/BitManipulation/389_FindtheDifference.c @@ -2,17 +2,10 @@ char findTheDifference(char *s, char *t) { - - // 每個字母代表一個數字 int ret = 0; - for (int i = 0; s[i] != '\0'; ++i) - { - ret ^= (s[i] - 'a'); - } - for (int i = 0; t[i] != '\0'; ++i) - { - ret ^= (t[i] - 'a'); - } + ret += (t[i] - 'a'); + for (int i = 0; s[i] != '\0'; ++i) + ret -= (s[i] - 'a'); return (char)(ret + 'a'); } \ No newline at end of file diff --git a/C/461_HammingDistance.c b/C/BitManipulation/461_HammingDistance.c similarity index 55% rename from C/461_HammingDistance.c rename to C/BitManipulation/461_HammingDistance.c index 44996d9..2e61ddf 100644 --- a/C/461_HammingDistance.c +++ b/C/BitManipulation/461_HammingDistance.c @@ -3,12 +3,11 @@ int hammingDistance(int x, int y) { int ret = 0; - while (x != y) + + for (int i = 0; i < 31; ++i) { - if ((x & 1) ^ (y & 1)) + if (((x >> i) & 1) ^ ((y >> i) & 1)) ret++; - x >>= 1; - y >>= 1; } return ret; } \ No newline at end of file diff --git a/C/476_NumberComplement.c b/C/BitManipulation/476_NumberComplement.c similarity index 62% rename from C/476_NumberComplement.c rename to C/BitManipulation/476_NumberComplement.c index 48a32f3..d1ccb22 100644 --- a/C/476_NumberComplement.c +++ b/C/BitManipulation/476_NumberComplement.c @@ -2,19 +2,19 @@ int findComplement(int num) { - // flip number - int n = num, i = 0; - while (n) + int x = num, i = 0; + while (x) { i++; - n >>= 1; + x >>= 1; } int mask = 0; while (i) { - mask <<= 1; - mask += 1; i--; + mask <<= 1; + mask++; } + return num ^ mask; } \ No newline at end of file diff --git a/C/645_SetMismatch.c b/C/BitManipulation/645_SetMismatch.c similarity index 90% rename from C/645_SetMismatch.c rename to C/BitManipulation/645_SetMismatch.c index a08a0f2..8dbe8f6 100644 --- a/C/645_SetMismatch.c +++ b/C/BitManipulation/645_SetMismatch.c @@ -5,10 +5,8 @@ */ int *findErrorNums(int *nums, int numsSize, int *returnSize) { - *returnSize = 2; - int *ret = calloc(2, sizeof(int)); - + int *ret = calloc(*returnSize, sizeof(int)); for (int i = 0; i < numsSize; ++i) { int idx = abs(nums[i]) - 1; @@ -22,5 +20,6 @@ int *findErrorNums(int *nums, int numsSize, int *returnSize) if (nums[i] > 0) ret[1] = i + 1; } + return ret; } \ No newline at end of file diff --git a/C/BitManipulation/7_ReverseInteger.c b/C/BitManipulation/7_ReverseInteger.c new file mode 100644 index 0000000..4d8c9a4 --- /dev/null +++ b/C/BitManipulation/7_ReverseInteger.c @@ -0,0 +1,14 @@ + + +int reverse(int x) +{ + int ret = 0; + while (x != 0) + { + if (abs(ret) > INT_MAX / 10) + return 0; + ret = 10 * ret + (x % 10); + x /= 10; + } + return ret; +} \ No newline at end of file diff --git a/C/BitManipulation/868_BinaryGap.c b/C/BitManipulation/868_BinaryGap.c new file mode 100644 index 0000000..489835c --- /dev/null +++ b/C/BitManipulation/868_BinaryGap.c @@ -0,0 +1,23 @@ +#define max(a, b) ((a > b) ? a : b) + +int binaryGap(int n) +{ + int ret = 0, i = 0, j = 0; + while ((n & 1) == 0) + { + n >>= 1; + i++; + } + j = i; + while (n) + { + if (n & 1) + { + ret = max(ret, i - j); + j = i; + } + i++; + n >>= 1; + } + return ret; +} \ No newline at end of file diff --git a/C/BitManipulation/89_GrayCode.c b/C/BitManipulation/89_GrayCode.c new file mode 100644 index 0000000..ee5d016 --- /dev/null +++ b/C/BitManipulation/89_GrayCode.c @@ -0,0 +1,14 @@ + + +/** + * Note: The returned array must be malloced, assume caller calls free(). + */ +int* grayCode(int n, int* returnSize){ + *returnSize = 1<>1)^i; + } + return ret; + +} \ No newline at end of file diff --git a/C/1137_N-thTribonacciNumber.c b/C/DynamicProgramming/1137_N-thTribonacciNumber.c similarity index 56% rename from C/1137_N-thTribonacciNumber.c rename to C/DynamicProgramming/1137_N-thTribonacciNumber.c index c9281a6..fa43db1 100644 --- a/C/1137_N-thTribonacciNumber.c +++ b/C/DynamicProgramming/1137_N-thTribonacciNumber.c @@ -2,14 +2,12 @@ int tribonacci(int n) { - - // 0 1 1 2 4 7 13 24 - if (n < 2) - return n; - if (n == 2) + // 0 1 1 2 4 + if (n == 0) + return 0; + if (n == 2 || n == 1) return 1; - - int a = 0, b = 1, c = 1, d = 2; + int a = 0, b = 1, c = 1, d = a + b + c; for (int i = 3; i <= n; ++i) { d = a + b + c; diff --git a/C/DynamicProgramming/322_CoinChange.c b/C/DynamicProgramming/322_CoinChange.c new file mode 100644 index 0000000..5140260 --- /dev/null +++ b/C/DynamicProgramming/322_CoinChange.c @@ -0,0 +1,25 @@ +#define min(a, b) ((a < b) ? a : b) + +int coinChange(int *coins, int coinsSize, int amount) +{ + + // 0 1 2 3 4 5 6 7 8 9 10 11 + // 0 1 2 3 4 5 6 7 8 9 10 11 + // 0 1 1 2 2 3 3 4 4 5 5 6 + // 0 1 1 2 2 1 2 2 3 3 2 3 + + int *dp = calloc(amount + 1, sizeof(int)); + for (int i = 1; i < amount + 1; ++i) + dp[i] = amount + 1; + for (int i = 0; i < coinsSize; ++i) + { + for (int j = 1; j < amount + 1; ++j) + { + if (j >= coins[i]) + dp[j] = min(dp[j - coins[i]] + 1, dp[j]); + // printf("%d ", dp[j]); + } + // printf("\r"); + } + return dp[amount] == amount + 1 ? -1 : dp[amount]; +} \ No newline at end of file diff --git a/C/DynamicProgramming/509_FibonacciNumber.c b/C/DynamicProgramming/509_FibonacciNumber.c new file mode 100644 index 0000000..b851e13 --- /dev/null +++ b/C/DynamicProgramming/509_FibonacciNumber.c @@ -0,0 +1,17 @@ + + +int fib(int n) +{ + if (n == 0) + return 0; + if (n < 3) + return 1; + int a = 1, b = 1, c = a + b; + for (int i = 3; i <= n; ++i) + { + c = a + b; + a = b; + b = c; + } + return c; +} \ No newline at end of file diff --git a/C/DynamicProgramming/70_ClimbingStairs.c b/C/DynamicProgramming/70_ClimbingStairs.c new file mode 100644 index 0000000..5293243 --- /dev/null +++ b/C/DynamicProgramming/70_ClimbingStairs.c @@ -0,0 +1,16 @@ + + +int climbStairs(int n) +{ + // 1 2 3 5 + if (n < 3) + return n; + int a = 1, b = 2, c = a + b; + for (int i = 3; i <= n; ++i) + { + c = a + b; + a = b; + b = c; + } + return c; +} \ No newline at end of file diff --git a/C/DynamicProgramming/746_MinCostClimbingStairs.c b/C/DynamicProgramming/746_MinCostClimbingStairs.c new file mode 100644 index 0000000..075364e --- /dev/null +++ b/C/DynamicProgramming/746_MinCostClimbingStairs.c @@ -0,0 +1,27 @@ +#define min(a, b) ((a < b) ? a : b) + +int minCostClimbingStairs(int *cost, int costSize) +{ + // 10 15 20 + // 0 0 10 15 + + // 1 100 1 1 1 100 1 1 100 1 + // 0 0 1 2 2 3 3 4 4 5 6 + + // int *dp = calloc( 1 + costSize, sizeof(int)); + // dp[0]= 0; + // dp[1] = 0; + // for(int i=2;i<=costSize ;++i){ + // dp[i] = min(dp[i-2]+cost[i-2], dp[i-1]+cost[i-1]); + // } + // return dp[costSize]; + + int a = 0, b = 0, c = 0; + for (int i = 2; i <= costSize; ++i) + { + c = min(cost[i - 2] + a, cost[i - 1] + b); + a = b; + b = c; + } + return c; +} \ No newline at end of file diff --git a/C/DynamicProgramming/931_MinimumFallingPathSum.c b/C/DynamicProgramming/931_MinimumFallingPathSum.c new file mode 100644 index 0000000..170f1d1 --- /dev/null +++ b/C/DynamicProgramming/931_MinimumFallingPathSum.c @@ -0,0 +1,35 @@ +#define min(a, b) ((a < b) ? a : b) + +int minFallingPathSum(int **matrix, int matrixSize, int *matrixColSize) +{ + int **dp = calloc(matrixSize, sizeof(int *)); + for (int i = 0; i < matrixSize; ++i) + dp[i] = calloc(matrixSize, sizeof(int)); + int ret = INT_MAX; + for (int i = 0; i < *matrixColSize; ++i) + { + dp[0][i] = matrix[0][i]; + ret = min(ret, dp[0][i]); + } + if (matrixSize == 1) + return ret; + ret = INT_MAX; + for (int i = 1; i < matrixSize; ++i) + { + for (int j = 0; j < matrixColSize[i]; ++j) + { + dp[i][j] = matrix[i][j]; + if (j == 0) + dp[i][j] += min(dp[i - 1][j], dp[i - 1][j + 1]); + else if (j == matrixSize - 1) + dp[i][j] += min(dp[i - 1][j - 1], dp[i - 1][j]); + else + dp[i][j] += min(min(dp[i - 1][j - 1], dp[i - 1][j + 1]), dp[i - 1][j]); + // printf("%d ", dp[i][j]); + if (i == matrixSize - 1) + ret = min(ret, dp[i][j]); + } + // printf("\r"); + } + return ret; +} \ No newline at end of file diff --git a/C/DynamicProgramming/983_MinimumCostForTickets.c b/C/DynamicProgramming/983_MinimumCostForTickets.c new file mode 100644 index 0000000..29437d7 --- /dev/null +++ b/C/DynamicProgramming/983_MinimumCostForTickets.c @@ -0,0 +1,27 @@ +#define min(a, b) ((a < b) ? a : b) + +int mincostTickets(int *days, int daysSize, int *costs, int costsSize) +{ + + // 1 4 6 7 8 20 + // 0 2 4 6 8 10 12 + // 0 2 4 6 7 + + // 1 2 3 4 5 6 7 8 9 10 30 31 + // + + int *dp = calloc(daysSize + 1, sizeof(int)); + + for (int i = 1; i < daysSize + 1; ++i) + { + dp[i] = dp[i - 1] + costs[0]; + for (int j = 1; j <= i; ++j) + { + if (days[i - 1] - days[j - 1] < 7) + dp[i] = min(dp[i], dp[j - 1] + costs[1]); + if (days[i - 1] - days[j - 1] < 30) + dp[i] = min(dp[i], dp[j - 1] + costs[2]); + } + } + return dp[daysSize]; +} \ No newline at end of file diff --git a/C/141_LinkedListCycle.c b/C/linkedList/141_LinkedListCycle.c similarity index 80% rename from C/141_LinkedListCycle.c rename to C/linkedList/141_LinkedListCycle.c index fdea451..86d7ff4 100644 --- a/C/141_LinkedListCycle.c +++ b/C/linkedList/141_LinkedListCycle.c @@ -9,12 +9,13 @@ bool hasCycle(struct ListNode *head) { if (!head) return false; - struct ListNode *slow = head, *fast = head; + struct ListNode *slow, *fast; + slow = fast = head; while (fast && fast->next) { - slow = slow->next; fast = fast->next->next; - if (fast == slow) + slow = slow->next; + if (slow == fast) return true; } return false; diff --git a/C/142_LinkedListCycleII.c b/C/linkedList/142_LinkedListCycleII.c similarity index 84% rename from C/142_LinkedListCycleII.c rename to C/linkedList/142_LinkedListCycleII.c index 9bf0fe3..2f3fd24 100644 --- a/C/142_LinkedListCycleII.c +++ b/C/linkedList/142_LinkedListCycleII.c @@ -9,17 +9,18 @@ struct ListNode *detectCycle(struct ListNode *head) { if (!head) return NULL; - struct ListNode *slow = head, *fast = head; + struct ListNode *slow, *fast; + slow = fast = head; while (fast && fast->next) { - slow = slow->next; fast = fast->next->next; + slow = slow->next; if (slow == fast) break; } if (fast == NULL || fast->next == NULL) - return NULL; - fast = head; + return false; + slow = head; while (slow != fast) { fast = fast->next; diff --git a/C/linkedList/160_IntersectionofTwoLinkedLists.c b/C/linkedList/160_IntersectionofTwoLinkedLists.c new file mode 100644 index 0000000..d5cd50e --- /dev/null +++ b/C/linkedList/160_IntersectionofTwoLinkedLists.c @@ -0,0 +1,25 @@ +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * struct ListNode *next; + * }; + */ +struct ListNode *getIntersectionNode(struct ListNode *headA, struct ListNode *headB) +{ + struct ListNode *a = headA, *b = headB; + while (a != b) + { + if (!a && !b) + return NULL; + if (a == NULL) + a = headB; + else + a = a->next; + if (b == NULL) + b = headA; + else + b = b->next; + } + return a; +} \ No newline at end of file diff --git a/C/19_RemoveNthNodeFromEndofList.c b/C/linkedList/19_RemoveNthNodeFromEndofList.c similarity index 62% rename from C/19_RemoveNthNodeFromEndofList.c rename to C/linkedList/19_RemoveNthNodeFromEndofList.c index e570b6b..b869c84 100644 --- a/C/19_RemoveNthNodeFromEndofList.c +++ b/C/linkedList/19_RemoveNthNodeFromEndofList.c @@ -8,18 +8,20 @@ struct ListNode *removeNthFromEnd(struct ListNode *head, int n) { - - struct ListNode *slow = malloc(sizeof(struct ListNode)), *fast = slow, *ret = slow; - slow->next = head; - while (n--) + struct ListNode *pre = (struct ListNode *)malloc(sizeof(struct ListNode)); + pre->next = head; + struct ListNode *slow, *fast; + slow = fast = pre; + while (n) { + n--; fast = fast->next; } while (fast->next) { - fast = fast->next; slow = slow->next; + fast = fast->next; } slow->next = slow->next->next; - return ret->next; + return pre->next; } \ No newline at end of file diff --git a/C/linkedList/206_ReverseLinkedList.c b/C/linkedList/206_ReverseLinkedList.c new file mode 100644 index 0000000..7f0270d --- /dev/null +++ b/C/linkedList/206_ReverseLinkedList.c @@ -0,0 +1,33 @@ +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * struct ListNode *next; + * }; + */ + +struct ListNode *reverseList(struct ListNode *head) +{ + // iteratively + // if(!head ||!head->next) return head; + // struct ListNode *pre = (struct ListNode*)malloc(sizeof(struct ListNode)); + // pre->next = head; + // struct ListNode * cur = head; + // while(cur->next){ + // struct ListNode *temp = cur->next; + // cur->next = temp->next; + // temp->next = pre->next; + // pre->next = temp; + // } + // return pre->next; + + // recursively + if (!head) + return NULL; + if (!head->next) + return head; + struct ListNode *node = reverseList(head->next); + head->next->next = head; + head->next = NULL; + return node; +} \ No newline at end of file diff --git a/C/linkedList/21_MergeTwoSortedLists.c b/C/linkedList/21_MergeTwoSortedLists.c new file mode 100644 index 0000000..4eb814e --- /dev/null +++ b/C/linkedList/21_MergeTwoSortedLists.c @@ -0,0 +1,33 @@ +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * struct ListNode *next; + * }; + */ + +struct ListNode *mergeTwoLists(struct ListNode *list1, struct ListNode *list2) +{ + if (!list1 && !list2) + return NULL; + struct ListNode *ret = (struct ListNode *)malloc(sizeof(struct ListNode)), *ans = ret; + while (list1 && list2) + { + if (list1->val < list2->val) + { + ret->next = list1; + list1 = list1->next; + } + else + { + ret->next = list2; + list2 = list2->next; + } + ret = ret->next; + } + if (list1) + ret->next = list1; + if (list2) + ret->next = list2; + return ans->next; +} \ No newline at end of file diff --git a/C/linkedList/234_PalindromeLinkedList.c b/C/linkedList/234_PalindromeLinkedList.c new file mode 100644 index 0000000..003bda1 --- /dev/null +++ b/C/linkedList/234_PalindromeLinkedList.c @@ -0,0 +1,57 @@ +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * struct ListNode *next; + * }; + */ + +struct ListNode *left; +bool traverse(struct ListNode *right) +{ + if (right == NULL) + return true; + bool ret = traverse(right->next); + if (right->val != left->val) + return false; + left = left->next; + return ret; +} +bool isPalindrome(struct ListNode *head) +{ + // left = head; + // return traverse(head->next); + + if (!head || !head->next) + return true; + struct ListNode *slow, *fast; + slow = fast = head; + while (fast->next && fast->next->next) + { + slow = slow->next; + fast = fast->next->next; + } + // slow = slow->next; + struct ListNode *cur = slow, *pre = NULL, *post = slow->next; + while (post) + { + cur->next = pre; + pre = cur; + cur = post; + post = post->next; + } + + cur->next = pre; + + slow = cur; + cur = head; + + while (slow->next) + { + if (cur->val != slow->val) + return false; + cur = cur->next; + slow = slow->next; + } + return true; +} \ No newline at end of file diff --git a/C/linkedList/25_ReverseNodesink-Group.c b/C/linkedList/25_ReverseNodesink-Group.c new file mode 100644 index 0000000..4a372bb --- /dev/null +++ b/C/linkedList/25_ReverseNodesink-Group.c @@ -0,0 +1,36 @@ +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * struct ListNode *next; + * }; + */ + +struct ListNode *reverse(struct ListNode *l, struct ListNode *r) +{ + struct ListNode *cur = l; + struct ListNode *pre = NULL; + while (cur != r) + { + struct ListNode *temp = cur->next; + cur->next = pre; + pre = cur; + cur = temp; + } + return pre; +} + +struct ListNode *reverseKGroup(struct ListNode *head, int k) +{ + struct ListNode *a, *b; + a = b = head; + for (int i = 0; i < k; ++i) + { + if (b == NULL) + return head; + b = b->next; + } + struct ListNode *newhead = reverse(a, b); + a->next = reverseKGroup(b, k); + return newhead; +} \ No newline at end of file diff --git a/C/876_MiddleoftheLinkedList.c b/C/linkedList/876_MiddleoftheLinkedList.c similarity index 72% rename from C/876_MiddleoftheLinkedList.c rename to C/linkedList/876_MiddleoftheLinkedList.c index fbb8ab5..3910ad0 100644 --- a/C/876_MiddleoftheLinkedList.c +++ b/C/linkedList/876_MiddleoftheLinkedList.c @@ -8,7 +8,10 @@ struct ListNode *middleNode(struct ListNode *head) { - struct ListNode *slow = head, *fast = head; + if (!head || !head->next) + return head; + struct ListNode *slow, *fast; + slow = fast = head; while (fast && fast->next) { slow = slow->next; diff --git a/C/linkedList/92_ReverseLinkedListII.c b/C/linkedList/92_ReverseLinkedListII.c new file mode 100644 index 0000000..18a88d2 --- /dev/null +++ b/C/linkedList/92_ReverseLinkedListII.c @@ -0,0 +1,32 @@ +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * struct ListNode *next; + * }; + */ + +struct ListNode *reverseN(struct ListNode *head, int right) +{ + struct ListNode *pre = (struct ListNode *)malloc(sizeof(struct ListNode)); + pre->next = head; + struct ListNode *cur = head; + for (int i = 0; i < right; ++i) + { + struct ListNode *temp = cur->next; + cur->next = temp->next; + temp->next = pre->next; + pre->next = temp; + } + return pre->next; +} + +struct ListNode *reverseBetween(struct ListNode *head, int left, int right) +{ + if (!head || !head->next) + return head; + if (left == 1) + return reverseN(head, right - 1); + head->next = reverseBetween(head->next, left - 1, right - 1); + return head; +} \ No newline at end of file diff --git a/C/nSum/15_3Sum.cpp b/C/nSum/15_3Sum.cpp new file mode 100644 index 0000000..990ac42 --- /dev/null +++ b/C/nSum/15_3Sum.cpp @@ -0,0 +1,37 @@ +class Solution +{ +public: + vector > threeSum(vector &nums) + { + vector > ret; + sort(nums.begin(), nums.end()); + int n = nums.size(); + for (int i = 0; i < n - 2; ++i) + { + if (i > 0 && nums[i] == nums[i - 1]) + continue; + + int j = i + 1, k = n - 1; + while (j < k) + { + int sum = nums[i] + nums[j] + nums[k]; + if (sum == 0) + { + ret.push_back({nums[i], nums[j], nums[k]}); + + while (j < k && nums[j] == nums[j + 1]) + j++; + while (j < k && nums[k] == nums[k - 1]) + k--; + j++; + k--; + } + else if (sum < 0) + j++; + else + k--; + } + } + return ret; + } +}; \ No newline at end of file diff --git a/C_plus/18*_4Sum.cpp b/C/nSum/18_4Sum.cpp similarity index 79% rename from C_plus/18*_4Sum.cpp rename to C/nSum/18_4Sum.cpp index cc86dbe..8981ca7 100644 --- a/C_plus/18*_4Sum.cpp +++ b/C/nSum/18_4Sum.cpp @@ -3,26 +3,23 @@ class Solution public: vector > fourSum(vector &nums, int target) { - // O(n^3) time and O(1) space + vector > ret; sort(nums.begin(), nums.end()); int n = nums.size(); - vector > ret; for (int i = 0; i < n - 3; ++i) { - if (i > 0 && nums[i - 1] == nums[i]) + if (i > 0 && nums[i] == nums[i - 1]) continue; for (int j = i + 1; j < n - 2; ++j) { - if (j > i + 1 && nums[j - 1] == nums[j]) + if (j > i + 1 && nums[j] == nums[j - 1]) continue; - int l = j + 1, r = n - 1; - int sum = target - nums[i] - nums[j]; - // avoid overflow while (l < r) { + int sum = target - nums[i] - nums[j]; int eval = nums[l] + nums[r]; - if (eval == sum) + if (sum == eval) { ret.push_back({nums[i], nums[j], nums[l], nums[r]}); while (l < r && nums[l] == nums[l + 1]) diff --git a/C/nSum/454_4SumII.cpp b/C/nSum/454_4SumII.cpp new file mode 100644 index 0000000..e14b301 --- /dev/null +++ b/C/nSum/454_4SumII.cpp @@ -0,0 +1,27 @@ +class Solution +{ +public: + int fourSumCount(vector &nums1, vector &nums2, vector &nums3, vector &nums4) + { + unordered_map mp; + for (int i = 0; i < nums1.size(); ++i) + { + for (int j = 0; j < nums2.size(); ++j) + { + int sum = nums1[i] + nums2[j]; + mp[-sum]++; + } + } + int ret = 0; + for (int i = 0; i < nums3.size(); ++i) + { + for (int j = 0; j < nums4.size(); ++j) + { + int sum = nums3[i] + nums4[j]; + if (mp.count(sum)) + ret += mp[sum]; + } + } + return ret; + } +}; \ No newline at end of file diff --git a/C/note.md b/C/note.md deleted file mode 100644 index aeb61d3..0000000 --- a/C/note.md +++ /dev/null @@ -1,22 +0,0 @@ - - - - -finished -Linked List [206 92] [141 142 876 19] -Binary Tree 226 114 116 105 106 -BST 538 450 701 700 -Array 1 167 344 316 [26 83 27 283 203] [349 350] -Binary search 704 34 875 1011 410 - -dp -- Subarray [53 152 978 1749] - - - -not yet - -234 25 -652 -230 98 96 -380 349 350 1002 diff --git a/C_plus/10*_RegularExpressionMatching.cpp b/C_plus/10*_RegularExpressionMatching.cpp deleted file mode 100644 index 0e51d69..0000000 --- a/C_plus/10*_RegularExpressionMatching.cpp +++ /dev/null @@ -1,73 +0,0 @@ -class Solution { -public: - unordered_map memo; - - bool dp(string &s, int i , string &p, int j){ - int m = s.size(), n = p.size(); - // base case - if(j==n) return i==m; - - if(i== m){ - if( (n-j) %2==1) return false; - - for(;j+0 commonChars(vector &words) - { - - // option 1 - vector rec(26, INT_MAX); - vector ret; - for (string word : words) - { - vector t(26); - for (char c : word) - t[c - 'a']++; - for (int i = 0; i < 26; i++) - rec[i] = min(rec[i], t[i]); - } - - for (int i = 0; i < 26; ++i) - { - for (int j = 0; j < rec[i]; ++j) - { - ret.push_back(string(1, 'a' + i)); - } - } - return ret; - } -}; \ No newline at end of file diff --git a/C_plus/1008*_ConstructBinarySearchTreefromPreorderTraversal.cpp b/C_plus/1008*_ConstructBinarySearchTreefromPreorderTraversal.cpp deleted file mode 100644 index 44c1118..0000000 --- a/C_plus/1008*_ConstructBinarySearchTreefromPreorderTraversal.cpp +++ /dev/null @@ -1,32 +0,0 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution -{ -public: - TreeNode *bstFromPreorder(vector &preorder, int l, int r) - { - if (l == r) - return nullptr; - TreeNode *root = new TreeNode(preorder[l]); // V - int i = l + 1; - while (i < r && preorder[i] < root->val) - i++; - root->left = bstFromPreorder(preorder, l + 1, i); // L - root->right = bstFromPreorder(preorder, i, r); // R - return root; - } - TreeNode *bstFromPreorder(vector &preorder) - { - - return bstFromPreorder(preorder, 0, preorder.size()); - } -}; \ No newline at end of file diff --git a/C_plus/100_SameTree.cpp b/C_plus/100_SameTree.cpp deleted file mode 100644 index aa1ddac..0000000 --- a/C_plus/100_SameTree.cpp +++ /dev/null @@ -1,25 +0,0 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution -{ -public: - bool isSameTree(TreeNode *p, TreeNode *q) - { - if (p == nullptr && q == nullptr) - return true; - else if (!q || !p) - return false; - else if (p->val == q->val) - return isSameTree(p->left, q->left) && isSameTree(p->right, q->right); - return false; - } -}; \ No newline at end of file diff --git a/C_plus/1011*_CapacityToShipPackagesWithinDDays.cpp b/C_plus/1011*_CapacityToShipPackagesWithinDDays.cpp deleted file mode 100644 index 0f0e24e..0000000 --- a/C_plus/1011*_CapacityToShipPackagesWithinDDays.cpp +++ /dev/null @@ -1,65 +0,0 @@ -class Solution -{ -public: - int f(vector &weights, int x) - { - // 定義:當運載能力為x 時,需要f(x)天才能完成運完所有貨物 - // f(weights, 10) = 7 , f(weights, 12) = 6 - // 隨著x 增加,f() 越小,單調遞增函數 - // 1 2 3 4 | 5 | 6 | 7 | 8 | 9 | 10 | - // days = 1 | 2 | 3 | 4 | 5 | 6 | 7 | , x= 10 - // days = 1 | 2 | 3 | 4 | 5 | 6 | , x= 12 - - int days = 0; - - for (int i = 0; i < weights.size();) - { - int cap = x; - - while (i < weights.size()) - { - if (cap < weights[i]) - break; - else - cap -= weights[i]; - i++; - } - days++; - } - - return days; - } - int shipWithinDays(vector &weights, int days) - { - - // 初始化left, right - // 船的最小載重 是 貨物最大值,最大載重一定是 所有貨物總重 - int left = 0, right = 1; - for (int w : weights) - { - left = max(left, w); - right += w; - } - - // 窮舉法 - for (int i = left; i <= right; ++i) - { - int target = f(weights, i); - if (target <= days) - return i; - } - - // 左側邊界 二元搜尋 - // while(left < right){ - // // 一開始假設 1 + (501-1)/2 = 船的容量 251,則一天就可以元算完, - // // 迭代式逼近 預估天數小於等於 days - // // 假設船的容量是mid,則需要f(weights, mid)天可運完。 - // int mid = left + (right - left)/2; - // int evalDays = f(weights, mid); - // if(evalDays <= days) right = mid ; - // else left = mid +1 ; - // } - - return left; - } -}; \ No newline at end of file diff --git a/C_plus/1014*_BestSightseeingPair.cpp b/C_plus/1014*_BestSightseeingPair.cpp deleted file mode 100644 index df8552c..0000000 --- a/C_plus/1014*_BestSightseeingPair.cpp +++ /dev/null @@ -1,25 +0,0 @@ -class Solution -{ -public: - int maxScoreSightseeingPair(vector &values) - { - - // brute force => time out - // int ret = 0, n = values.size(); - // for(int i=0;i nextLargerNodes(ListNode *head) - { - // option 1 O(n^2) timeout - // vector tmp; - // for(ListNode *p=head;p;p=p->next){ - // tmp.emplace_back(p->val); - // } - // vector ret ; - // for(int i=0;i sta; - int _max = 0; - vector nums; - for (ListNode *p = head; p; p = p->next) - nums.emplace_back(p->val); - vector ret(nums.size(), 0); - for (int i = 0; i < nums.size(); ++i) - { - - while (!sta.empty() && nums[i] > nums[sta.top()]) - { - ret[sta.top()] = nums[i]; - sta.pop(); - } - sta.push(i); - cout << sta.top() << endl; - } - return ret; - } -}; \ No newline at end of file diff --git a/C_plus/101_SymmetricTree.cpp b/C_plus/101_SymmetricTree.cpp deleted file mode 100644 index 4d50163..0000000 --- a/C_plus/101_SymmetricTree.cpp +++ /dev/null @@ -1,31 +0,0 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution -{ -public: - bool symmteric(TreeNode *left, TreeNode *right) - { - if (!left && !right) - return true; - else if (!left || !right) - return false; - if (left->val == right->val) - { - return symmteric(left->right, right->left) && symmteric(right->right, left->left); - } - return false; - } - bool isSymmetric(TreeNode *root) - { - return symmteric(root->left, root->right); - } -}; \ No newline at end of file diff --git a/C_plus/1020_NumberofEnclaves.cpp b/C_plus/1020_NumberofEnclaves.cpp deleted file mode 100644 index 785d0c5..0000000 --- a/C_plus/1020_NumberofEnclaves.cpp +++ /dev/null @@ -1,50 +0,0 @@ -class Solution -{ -public: - void dfs(vector > &grid, int i, int j, int &area) - { - int n = grid.size(), m = grid[0].size(); - if (i < 0 || j < 0 || i > n - 1 || j > m - 1 || grid[i][j] == 0) - return; - - grid[i][j] = 0; - area++; - dfs(grid, i - 1, j, area); - dfs(grid, i, j - 1, area); - dfs(grid, i + 1, j, area); - dfs(grid, i, j + 1, area); - } - int numEnclaves(vector > &grid) - { - - // 先將周圍島嶼淹掉,再計算剩餘島嶼的總面積大小 - int n = grid.size(), m = grid[0].size(); - int totalArea = 0, area; - for (int i = 0; i < n; ++i) - { - dfs(grid, i, 0, area); - dfs(grid, i, m - 1, area); - } - for (int j = 0; j < m; ++j) - { - dfs(grid, 0, j, area); - dfs(grid, n - 1, j, area); - } - - for (int i = 0; i < n; ++i) - { - for (int j = 0; j < m; ++j) - { - // option 1 - // if(grid[i][j] == 0) continue; - // area = 0; - // dfs(grid, i, j, area); - // totalArea += area; - - //option 2 - totalArea += (grid[i][j] == 1); - } - } - return totalArea; - } -}; \ No newline at end of file diff --git a/C_plus/1022*_SumofRootToLeafBinaryNumbers.cpp b/C_plus/1022*_SumofRootToLeafBinaryNumbers.cpp deleted file mode 100644 index d9d8717..0000000 --- a/C_plus/1022*_SumofRootToLeafBinaryNumbers.cpp +++ /dev/null @@ -1,62 +0,0 @@ -/* - * @Author: yuan - * @Date: 2021-07-17 10:19:00 - * @LastEditTime: 2021-07-17 10:19:01 - * @FilePath: /leet_code/C_plus/1022*_SumofRootToLeafBinaryNumbers.cpp - */ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution -{ -public: - void path(TreeNode *root, vector &cand, int tmp) - { - if (!root) - return; - - tmp *= 2; - tmp += root->val; - - if (root->left == nullptr && root->right == nullptr) - { - cand.push_back(tmp); - } - path(root->left, cand, tmp); - path(root->right, cand, tmp); - } - int sumRootToLeaf(TreeNode *root) - { - // option 1 - // vector cand; - // path(root, cand,0); - // int ans =0 ; - // for(int n:cand) ans +=n; - // return ans; - - //option 1.1 - int ans = 0; - pathSum(root, 0, ans); - return ans; - } - void pathSum(TreeNode *root, int cur, int &ans) - { - if (!root) - return; - - cur = 2 * cur + root->val; - if (root->left == nullptr && root->right == nullptr) - ans += cur; - - pathSum(root->left, cur, ans); - pathSum(root->right, cur, ans); - } -}; \ No newline at end of file diff --git a/C_plus/1024*_VideoStitching.cpp b/C_plus/1024*_VideoStitching.cpp deleted file mode 100644 index fd5539a..0000000 --- a/C_plus/1024*_VideoStitching.cpp +++ /dev/null @@ -1,43 +0,0 @@ -class Solution -{ -public: - int videoStitching(vector > &clips, int time) - { - // 區間問題一律按照起點或終點排序。 - - // step1. 先照起點升序,起點一致再用終點作降序 - // 因為clip 起點相同,那一定選最長的。這就是貪心的策略。 - // step2. 選定第一個clips[0]當作起點,比較所有起點小於clips[0][1]的區間。 - // 根據貪心策略,他們中終點最大的即是第二個clip小影片,再從第二個clip貪心選擇第三個以此類推。 - // step3. 重複step2 直到覆蓋區間[0,time]或是無法覆蓋則返回-1。 - sort(clips.begin(), clips.end(), [](vector &a, vector &b) - { - if (a[0] == b[0]) - return a[1] > b[1]; - return a[0] < b[0]; - }); - if (clips.size() == 0 || time == 0) - return 0; - // 紀錄選擇的clip個數 - int count = 0; - int curEnd = 0, nextEnd = 0; - int i = 0, n = clips.size(); - while (i < n && clips[i][0] <= curEnd) - { // 第一個區間必定是0當作起點 - - // 選擇下一個clip - while (i < n && clips[i][0] <= curEnd) - { - nextEnd = max(nextEnd, clips[i][1]); - i++; - } - //找到下一個clip,更新curEnd - count++; - curEnd = nextEnd; - // 表示已經可以拼接出 [0,time] - if (curEnd >= time) - return count; - } - return -1; - } -}; \ No newline at end of file diff --git a/C_plus/1025*_DivisorGame.cpp b/C_plus/1025*_DivisorGame.cpp deleted file mode 100644 index 5db70b8..0000000 --- a/C_plus/1025*_DivisorGame.cpp +++ /dev/null @@ -1,29 +0,0 @@ -class Solution -{ -public: - bool divisorGame(int n) - { - // option 1 dp - vector dp(n + 1); - // 起始數字為i,Alice是否會贏 - dp[0] = false; - dp[1] = false; - for (int i = 2; i <= n; ++i) - { - for (int j = 1; j < i; ++j) - { - if (i % j != 0) - continue; - if (dp[i - j] == false) - { - dp[i] = true; - break; - } - } - } - return dp[n]; - - // option 2 拿到1必輸,拿到2則贏 - // return n%2==0; - } -}; \ No newline at end of file diff --git a/C_plus/102_BinaryTreeLevelOrderTraversal.cpp b/C_plus/102_BinaryTreeLevelOrderTraversal.cpp deleted file mode 100644 index 7cbd7a8..0000000 --- a/C_plus/102_BinaryTreeLevelOrderTraversal.cpp +++ /dev/null @@ -1,43 +0,0 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution -{ -public: - vector > levelOrder(TreeNode *root) - { - vector > ret; - if (!root) - return ret; - queue q; - q.push(root); - int number_of_node_level; - while (!q.empty()) - { - number_of_node_level = q.size(); - vector temp; - while (number_of_node_level) - { - TreeNode *t = q.front(); - q.pop(); - temp.push_back(t->val); - - if (t->left) - q.push(t->left); - if (t->right) - q.push(t->right); - number_of_node_level--; - } - ret.push_back(temp); - } - return ret; - } -}; \ No newline at end of file diff --git a/C_plus/1035*_UncrissedLines.cpp b/C_plus/1035*_UncrissedLines.cpp deleted file mode 100644 index de8b1cb..0000000 --- a/C_plus/1035*_UncrissedLines.cpp +++ /dev/null @@ -1,29 +0,0 @@ -class Solution -{ -public: - int maxUncrossedLines(vector &nums1, vector &nums2) - { - // option 1 dp from hint 1 O(MN) time and O(MN) space - int a = nums1.size(), b = nums2.size(); - vector > dp(a + 1, vector(b + 1, 0)); - for (int i = 1; i <= a; ++i) - { - for (int j = 1; j <= b; ++j) - { - if (nums1[i - 1] == nums2[j - 1]) - { - // dp[i][j] = 1+ min(dp[i-1][j], dp[i][j-1]); - dp[i][j] = 1 + dp[i - 1][j - 1]; - } - else - { - dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]); - } - } - } - return dp[a][b]; - - // option 2 1-D dp + max() O(MN) time and O(N) space - // option 3 recursion - } -}; \ No newline at end of file diff --git a/C_plus/1038*_BinarySearchTreetoGreaterSumTree.cpp b/C_plus/1038*_BinarySearchTreetoGreaterSumTree.cpp deleted file mode 100644 index c3bc027..0000000 --- a/C_plus/1038*_BinarySearchTreetoGreaterSumTree.cpp +++ /dev/null @@ -1,33 +0,0 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution { -private: - int sum = 0; -public: - - void traverse(TreeNode * root){ - // base case - if(!root) return ; - // R - traverse(root->right); - // V - sum +=root->val; - root->val = sum; - // L - traverse(root->left); - } - TreeNode* bstToGst(TreeNode* root) { - traverse(root); - return root; - - } -}; \ No newline at end of file diff --git a/C_plus/103_BinaryTreeZigzagLevelOrderTraversal.cpp b/C_plus/103_BinaryTreeZigzagLevelOrderTraversal.cpp deleted file mode 100644 index f1822f9..0000000 --- a/C_plus/103_BinaryTreeZigzagLevelOrderTraversal.cpp +++ /dev/null @@ -1,51 +0,0 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution -{ -public: - vector > zigzagLevelOrder(TreeNode *root) - { - // level order traverse - if (!root) - return {}; - vector > ret; - int flag = 1; // 1 left to right - queue q; - q.push(root); - while (!q.empty()) - { - int size = q.size(); - vector tmp; - for (int i = 0; i < size; ++i) - { - TreeNode *p = q.front(); - q.pop(); - if (flag == 1) - { - tmp.push_back(p->val); - } - else - { - tmp.insert(tmp.begin(), p->val); - } - - if (p->left) - q.push(p->left); - if (p->right) - q.push(p->right); - } - ret.push_back(tmp); - flag *= -1; - } - return ret; - } -}; \ No newline at end of file diff --git a/C_plus/1046_LastStoneWeight.cpp b/C_plus/1046_LastStoneWeight.cpp deleted file mode 100644 index 3792e19..0000000 --- a/C_plus/1046_LastStoneWeight.cpp +++ /dev/null @@ -1,23 +0,0 @@ -class Solution -{ -public: - int lastStoneWeight(vector &stones) - { - // use STL priority_queue O(nlogn) - int ret = 0; - priority_queue q; - for (int i : stones) - q.push(i); - - while (q.size() > 1) - { - int y = q.top(); - q.pop(); - int x = q.top(); - q.pop(); - int sum = y - x; - q.push(sum); - } - return q.top(); - } -}; \ No newline at end of file diff --git a/C_plus/1047_RemoveAllAdjacentDuplicatesInString.cpp b/C_plus/1047_RemoveAllAdjacentDuplicatesInString.cpp deleted file mode 100644 index 004a62e..0000000 --- a/C_plus/1047_RemoveAllAdjacentDuplicatesInString.cpp +++ /dev/null @@ -1,41 +0,0 @@ -class Solution -{ -public: - string removeDuplicates(string s) - { - // option 1 use stack to store O(n) - // stack c; - - // for(int i=0;i 0 && s[i - 1] == s[i]) i -= 2; - // } - // return s.substr(0, i); - } -}; \ No newline at end of file diff --git a/C_plus/104_MaximumDepthOfBinaryTree.cpp b/C_plus/104_MaximumDepthOfBinaryTree.cpp deleted file mode 100644 index 9334f30..0000000 --- a/C_plus/104_MaximumDepthOfBinaryTree.cpp +++ /dev/null @@ -1,43 +0,0 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution -{ -public: - int maxDepth(TreeNode *root) - { - // option 1 recursive DFS - // if(!root) return 0; - // return 1+ max(maxDepth(root->left), maxDepth(root->right)); - - // optnio 2 iterative BFS + queue - if (!root) - return 0; - queue q; - q.push(root); - int step = 0; - while (!q.empty()) - { - int size = q.size(); - for (int i = 0; i < size; ++i) - { - TreeNode *p = q.front(); - q.pop(); - if (p->left) - q.push(p->left); - if (p->right) - q.push(p->right); - } - step++; - } - return step; - } -}; \ No newline at end of file diff --git a/C_plus/105*_ConstructBinaryTreefromPreorderandInorderTraversal.cpp b/C_plus/105*_ConstructBinaryTreefromPreorderandInorderTraversal.cpp deleted file mode 100644 index c0f10be..0000000 --- a/C_plus/105*_ConstructBinaryTreefromPreorderandInorderTraversal.cpp +++ /dev/null @@ -1,42 +0,0 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution -{ -public: - TreeNode *buildTree(vector &preorder, int lo, int hi, vector &inorder, int l, int r) - { - - if (lo > hi || l > r) - return nullptr; - TreeNode *root = new TreeNode(preorder[lo]); - - int idx = -1, val = preorder[lo]; - for (int i = l; i <= r; ++i) - { - if (val == inorder[i]) - { - idx = i; - break; - } - } - - root->left = buildTree(preorder, lo + 1, lo + idx - l, inorder, l, idx - 1); - root->right = buildTree(preorder, lo + idx - l + 1, hi, inorder, idx + 1, r); - return root; - } - - TreeNode *buildTree(vector &preorder, vector &inorder) - { - - return buildTree(preorder, 0, preorder.size() - 1, inorder, 0, inorder.size() - 1); - } -}; \ No newline at end of file diff --git a/C_plus/1051_HeightChecker.cpp b/C_plus/1051_HeightChecker.cpp deleted file mode 100644 index ecfed81..0000000 --- a/C_plus/1051_HeightChecker.cpp +++ /dev/null @@ -1,17 +0,0 @@ -class Solution -{ -public: - int heightChecker(vector &heights) - { - // option 1 O(nlogn) - int ret = 0; - vector vec(heights.begin(), heights.end()); - sort(vec.begin(), vec.end()); - for (int i = 0; i < vec.size(); ++i) - { - if (heights[i] != vec[i]) - ret++; - } - return ret; - } -}; \ No newline at end of file diff --git a/C_plus/106*_ConstructBinaryTreefromInorderandPostorderTraversal.cpp b/C_plus/106*_ConstructBinaryTreefromInorderandPostorderTraversal.cpp deleted file mode 100644 index 493be99..0000000 --- a/C_plus/106*_ConstructBinaryTreefromInorderandPostorderTraversal.cpp +++ /dev/null @@ -1,43 +0,0 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution -{ -public: - TreeNode *buildTree(vector &inorder, vector &postorder, int il, int ir, int pl, int pr) - { - if (il > ir || pl > pr) - return nullptr; - // preorder traverse - // 從postorder最後一個元素找出root - TreeNode *root = new TreeNode(postorder[pr]); - // 從 inorder 找尋根節點,並切分出左右子樹的數組 - int index = 0; - for (int i = il; i <= ir; ++i) - { - if (inorder[i] == postorder[pr]) - { - index = i; - break; - } - } - - root->left = buildTree(inorder, postorder, il, index - 1, pl, pl + index - il - 1); - root->right = buildTree(inorder, postorder, index + 1, ir, pl + index - il, pr - 1); - - return root; - } - TreeNode *buildTree(vector &inorder, vector &postorder) - { - - return buildTree(inorder, postorder, 0, inorder.size() - 1, 0, postorder.size() - 1); - } -}; \ No newline at end of file diff --git a/C_plus/1071*_GreatestCommonDivisorofStrings.cpp b/C_plus/1071*_GreatestCommonDivisorofStrings.cpp deleted file mode 100644 index af0fd51..0000000 --- a/C_plus/1071*_GreatestCommonDivisorofStrings.cpp +++ /dev/null @@ -1,43 +0,0 @@ -class Solution -{ -public: - int gcd(int a, int b) - { - if (a == b) - return a; - if (a > b) - return gcd(a - b, a); - return gcd(a, b - a); - } - string gcdOfStrings(string str1, string str2) - { - // 找 兩字串長度的最大公因數 - - // option 1 iterative - if (str1 + str2 != str2 + str1) - return ""; - int a = str1.size(), b = str2.size(); - - while (a != b) - { - if (a < b) - { - b = b - a; - } - else if (a > b) - { - int tmp = a; - a = a - b; - b = tmp; - } - } - - return str1.substr(0, a); - - // option 2 recursive - // if(str1 + str2 != str2 + str1) return ""; - // int a = str1.size(), b = str2.size(); - // int g = gcd(a, b); - // return str1.substr(0,g); - } -}; \ No newline at end of file diff --git a/C_plus/107_BinaryTreeLevelOrderTraversalII.cpp b/C_plus/107_BinaryTreeLevelOrderTraversalII.cpp deleted file mode 100644 index 73ee9ea..0000000 --- a/C_plus/107_BinaryTreeLevelOrderTraversalII.cpp +++ /dev/null @@ -1,43 +0,0 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution -{ -public: - vector > levelOrderBottom(TreeNode *root) - { - queue q; - vector > ret; - if (!root) - return ret; - q.push(root); - - int number_of_node; - while (!q.empty()) - { - number_of_node = q.size(); - vector temp; - while (number_of_node) - { - number_of_node--; - TreeNode *cur = q.front(); - q.pop(); - temp.push_back(cur->val); - if (cur->left) - q.push(cur->left); - if (cur->right) - q.push(cur->right); - } - ret.insert(ret.begin(), temp); - } - return ret; - } -}; \ No newline at end of file diff --git a/C_plus/1080*_InsufficientNodesinRoottoLeafPaths.cpp b/C_plus/1080*_InsufficientNodesinRoottoLeafPaths.cpp deleted file mode 100644 index b36538d..0000000 --- a/C_plus/1080*_InsufficientNodesinRoottoLeafPaths.cpp +++ /dev/null @@ -1,38 +0,0 @@ -/* - * @Author: yuan - * @Date: 2021-07-16 13:51:53 - * @LastEditTime: 2021-07-16 13:52:01 - * @FilePath: /leet_code/C_plus/1080*_InsufficientNodesinRoottoLeafPaths.cpp - */ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution -{ -public: - TreeNode *sufficientSubset(TreeNode *root, int limit) - { - if (root->left == root->right) - { - return root->val < limit ? nullptr : root; - } - if (root->left) - { - root->left = sufficientSubset(root->left, limit - root->val); - } - if (root->right) - { - root->right = sufficientSubset(root->right, limit - root->val); - } - - return root->left == root->right ? nullptr : root; - } -}; \ No newline at end of file diff --git a/C_plus/1081*_SmallestSubsequenceofDistinctCharacters.cpp b/C_plus/1081*_SmallestSubsequenceofDistinctCharacters.cpp deleted file mode 100644 index 45ff934..0000000 --- a/C_plus/1081*_SmallestSubsequenceofDistinctCharacters.cpp +++ /dev/null @@ -1,40 +0,0 @@ -class Solution -{ -public: - string smallestSubsequence(string s) - { - vector count(256, 0); - vector instack(256, false); - stack sta; - - for (char c : s) - count[c]++; - - for (char c : s) - { - count[c]--; - - if (instack[c]) - continue; - - while (!sta.empty() && sta.top() > c) - { - if (count[sta.top()] == 0) - break; - instack[sta.top()] = false; - sta.pop(); - } - - instack[c] = true; - sta.push(c); - } - - string ret; - while (!sta.empty()) - { - ret.insert(ret.begin(), sta.top()); - sta.pop(); - } - return ret; - } -}; \ No newline at end of file diff --git a/C_plus/1089_DuplicateZeros.cpp b/C_plus/1089_DuplicateZeros.cpp deleted file mode 100644 index d6e8dac..0000000 --- a/C_plus/1089_DuplicateZeros.cpp +++ /dev/null @@ -1,42 +0,0 @@ -class Solution -{ -public: - void duplicateZeros(vector &arr) - { - // option 1 use STL queue O(n) - queue q; - for (int i = 0; i < arr.size(); ++i) - { - q.push(arr[i]); - if (arr[i] == 0) - q.push(arr[i]); - arr[i] = q.front(); - q.pop(); - } - - // option 2 cheat O(n) time O(n) space - // vector ret; - // int n =arr.size(); - // for(int i=0;i& nums) { - // 先決定root,再分兩部分left, right - if(nums.empty()) return nullptr; - int mid = nums.size()/2; - TreeNode *root = new TreeNode(nums[mid]); - vector left(nums.begin(), nums.begin()+mid); - vector right(nums.begin()+mid+1, nums.end()); - root->left = sortedArrayToBST(left); - root->right = sortedArrayToBST(right); - return root; - - } -}; \ No newline at end of file diff --git a/C_plus/109*_ConvertSortedListtoBinarySearchTree.cpp b/C_plus/109*_ConvertSortedListtoBinarySearchTree.cpp deleted file mode 100644 index a6ef2e1..0000000 --- a/C_plus/109*_ConvertSortedListtoBinarySearchTree.cpp +++ /dev/null @@ -1,79 +0,0 @@ -/** - * Definition for singly-linked list. - * struct ListNode { - * int val; - * ListNode *next; - * ListNode() : val(0), next(nullptr) {} - * ListNode(int x) : val(x), next(nullptr) {} - * ListNode(int x, ListNode *next) : val(x), next(next) {} - * }; - */ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution -{ -public: - TreeNode *sortedArrayToBST(vector &nums) - { - if (nums.empty()) - return nullptr; - - int mid = nums.size() / 2; - TreeNode *root = new TreeNode(nums[mid]); - vector left(nums.begin(), nums.begin() + mid); - vector right(nums.begin() + mid + 1, nums.end()); - root->left = sortedArrayToBST(left); - root->right = sortedArrayToBST(right); - return root; - } - TreeNode *sortedListToBST(ListNode *head) - { - // option 1 convert array and - if (!head) - return nullptr; - if (!head->next) - return new TreeNode(head->val); - int len = 0; - vector v; - ListNode *p = head; - while (p) - { - len++; - v.emplace_back(p->val); - p = p->next; - } - return sortedArrayToBST(v); - - // option 2 slow-fast pointer - // 先決定root,再分兩部分left, right - if (!head) - return nullptr; - // use slow fast to determine root node - ListNode *slow = head, *fast = head, *pre = nullptr; - - while (fast && fast->next) - { - pre = slow; - slow = slow->next; - fast = fast->next->next; - } - // partition - if (pre != nullptr) - pre->next = nullptr; - else - head = nullptr; - TreeNode *root = new TreeNode(slow->val); - root->left = sortedListToBST(head); - root->right = sortedListToBST(slow->next); - return root; - } -}; \ No newline at end of file diff --git a/C_plus/1091*_ShortestPathinBinaryMatrix.cpp b/C_plus/1091*_ShortestPathinBinaryMatrix.cpp deleted file mode 100644 index a1db9fc..0000000 --- a/C_plus/1091*_ShortestPathinBinaryMatrix.cpp +++ /dev/null @@ -1,43 +0,0 @@ -class Solution -{ -public: - int shortestPathBinaryMatrix(vector > &grid) - { - - // BFS - - int n = grid.size(), m = grid[0].size(); - if (grid[0][0] != 0 || grid[n - 1][m - 1] != 0) - return -1; - vector > acts = {{-1, -1}, {-1, 0}, {-1, 1}, {0, -1}, {0, 1}, {1, -1}, {1, 0}, {1, 1}}; - queue > q; - q.push({0, 0}); - int len = 1; - vector > visited(n, vector(m, false)); - visited[0][0] = true; - // directly change the visited cell to grid[i][j] = 1 to avoid repeatedly visiting. No need for boolean arr. - - while (!q.empty()) - { - int size = q.size(); - for (int i = 0; i < size; ++i) - { - vector p = q.front(); - if (p[0] == n - 1 && p[1] == m - 1) - return len; - q.pop(); - for (vector a : acts) - { - int x = p[0] + a[0]; - int y = p[1] + a[1]; - if (x < 0 || x > n - 1 || y < 0 || y > m - 1 || grid[x][y] == 1 || visited[x][y]) - continue; - q.push({x, y}); - visited[x][y] = true; - } - } - len++; - } - return -1; - } -}; \ No newline at end of file diff --git a/C_plus/110*_BalancedBinaryTree.cpp b/C_plus/110*_BalancedBinaryTree.cpp deleted file mode 100644 index a740620..0000000 --- a/C_plus/110*_BalancedBinaryTree.cpp +++ /dev/null @@ -1,54 +0,0 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution -{ -public: - int getHeight(TreeNode *root) - { - if (!root) - return 0; - return 1 + max(getHeight(root->left), getHeight(root->right)); - } - int checkHeight(TreeNode *root) - { - if (root == nullptr) - return -1; - int leftHeight = checkHeight(root->left); - if (leftHeight == INT_MIN) - return INT_MIN; // Pass error up - int rightHeight = checkHeight(root->right); - if (rightHeight == INT_MIN) - return INT_MIN; // Pass error up - - /* What do we use for an error code? The height of a null tree is generally defined to be -1, - so that's not a great idea for an error code. - Instead, we' ll use Integer. MIN_VALUE. */ - int heightDiff = leftHeight - rightHeight; - if (abs(heightDiff) > 1) - return INT_MIN; - else - return max(leftHeight, rightHeight) + 1; - } - bool isBalanced(TreeNode *root) - { - // option 1 O(N log N) time - // 1. get left child tree hight and right child tree height - // if(!root) return true; - // int heightDiff = getHeight(root->left) - getHeight(root->right); - // if(abs(heightDiff)>1 )return false; - // else return isBalanced(root->left) && isBalanced(root->right); - - // option 2 O(N) time and O(Height) space - return checkHeight(root) != INT_MIN; - } -}; - diff --git a/C_plus/1109*_CorporateFlightBookings.cpp b/C_plus/1109*_CorporateFlightBookings.cpp deleted file mode 100644 index 5fc69bc..0000000 --- a/C_plus/1109*_CorporateFlightBookings.cpp +++ /dev/null @@ -1,72 +0,0 @@ -class Difference -{ -private: - vector diff; - -public: - Difference(vector &nums) - { - diff = vector(nums.size(), 0); - // 建造差分數組 - diff[0] = nums[0]; - for (int i = 1; i < nums.size(); i++) - { - diff[i] = nums[i] - nums[i - 1]; - } - } - void increment(int i, int j, int val) - { - // 給閉區間 [i, j] 增加 val 可以是負數 - diff[i] += val; - // 相當於 inded = i 後的元素的 加val - if (j + 1 < diff.size()) - { - diff[j + 1] -= val; - } - // 相當於 inded = j+1 後的元素的 剪val - } - vector result() - { - // 根據差分數組建造結果數組 - vector ret(diff.size(), 0); - ret[0] = diff[0]; - for (int i = 1; i < diff.size(); i++) - { - ret[i] = ret[i - 1] + diff[i]; - } - return ret; - } -}; - -class Solution -{ -public: - vector corpFlightBookings(vector > &bookings, int n) - { - // option - // 差分 主要場景適用頻繁的對原數組的某區間的元素進行增減。 - // [1,2,10],[2,3,20],[2,5,25] - // 還原數組 => 10 55 45 25 25 - // option 1 timeout O(n^2) - // vector ret(n,0); - // for(auto vec:bookings){ - // int l = vec[0], r = vec[1], k = vec[2]; - // for(int i=l;i<=r;++i){ - // ret[i-1] += k; - // } - // } - // return ret; - - // option 2 - vector num(n, 0); - Difference *diff = new Difference(num); - for (vector book : bookings) - { - int i = book[0] - 1; - int j = book[1] - 1; - int val = book[2]; - diff->increment(i, j, val); - } - return diff->result(); - } -}; \ No newline at end of file diff --git a/C_plus/111_MinimumDepthOfBinaryTree.cpp b/C_plus/111_MinimumDepthOfBinaryTree.cpp deleted file mode 100644 index 62b0d6b..0000000 --- a/C_plus/111_MinimumDepthOfBinaryTree.cpp +++ /dev/null @@ -1,52 +0,0 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution -{ -public: - int minDepth(TreeNode *root) - { - // option 1 recursive DFS O(logn) space - // if(!root) return 0; - // if(!root->left) return 1+minDepth(root->right); - // if(!root->right) return 1+minDepth(root->left); - // return 1+min(minDepth(root->left), minDepth(root->right)); - - // option 2 BFS O(N) space - if (root == nullptr) - return 0; - queue q; - q.push(root); - int depth = 1; - while (!q.empty()) - { - int size = q.size(); - // 逐層探索 - for (int i = 0; i < size; ++i) - { - TreeNode *cur = q.front(); - q.pop(); - // 判斷是否到達終點 - if (cur->left == nullptr && cur->right == nullptr) - { - return depth; - } - if (cur->left) - q.push(cur->left); - if (cur->right) - q.push(cur->right); - } - // 完成一層探索,深度加一 - depth++; - } - return depth; - } -}; \ No newline at end of file diff --git a/C_plus/112_PathSum.cpp b/C_plus/112_PathSum.cpp deleted file mode 100644 index 35b2bd1..0000000 --- a/C_plus/112_PathSum.cpp +++ /dev/null @@ -1,74 +0,0 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution { -public: - - bool hasPathSum(TreeNode* root, int targetSum) { - // option 1 brute force DFS O(logN) - // if(!root) return false; - // if(root->val == targetSum && !root->left && !root->right) return true; - // int target = targetSum-root->val; - // return hasPathSum(root->left, target) || hasPathSum(root->right, target); - - // BFS + stack or queue -// if (!root) return false; -// stack sta{{root}}; - - -// while(!sta.empty()){ -// TreeNode *t = sta.top(); -// sta.pop(); -// if (!t->left && !t->right) { -// if (t->val == targetSum) return true; -// } -// if(t->right){ -// t->right->val += t->val; -// sta.push(t->right); -// } -// if(t->left){ -// t->left->val += t->val; -// sta.push(t->left); -// } - -// } -// return false; - - - //queue q; - - if (!root) return false; - queue q{{root}}; - - - while(!q.empty()){ - int size = q.size(); - for(int i=0;ileft && !t->right) { - if (t->val == targetSum) return true; - } - if(t->right){ - t->right->val += t->val; - q.push(t->right); - } - if(t->left){ - t->left->val += t->val; - q.push(t->left); - } - } - } - return false; - - - } -}; \ No newline at end of file diff --git a/C_plus/113*_PathSunII.cpp b/C_plus/113*_PathSunII.cpp deleted file mode 100644 index f3ec6fd..0000000 --- a/C_plus/113*_PathSunII.cpp +++ /dev/null @@ -1,55 +0,0 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution -{ -public: - void traverse(TreeNode *root, int target, vector &path, vector > &ret) - { - - if (!root) - return; - - path.push_back(root->val); - target -= root->val; - - if (!root->left && !root->right) - { - if (target == 0) - { - ret.push_back(path); - } - return; - } - - if (root->left) - { - traverse(root->left, target, path, ret); - path.pop_back(); - } - if (root->right) - { - traverse(root->right, target, path, ret); - path.pop_back(); - } - } - vector > pathSum(TreeNode *root, int targetSum) - { - - vector > ret; - vector path; - traverse(root, targetSum, path, ret); - return ret; - } - // option 2 BFS -} -} -; \ No newline at end of file diff --git a/C_plus/1137_N-thTribonacciNumber.cpp b/C_plus/1137_N-thTribonacciNumber.cpp deleted file mode 100644 index f76ec5a..0000000 --- a/C_plus/1137_N-thTribonacciNumber.cpp +++ /dev/null @@ -1,27 +0,0 @@ -class Solution { -public: - int tribonacci(int n) { - // option 1 - // if(n==0) return 0; - // if(n==1 || n==2) return 1; - // int a = 0, b=1,c=1,ret; - // for(int i=3;i<=n;++i){ - // ret = a+b+c; - // a = b; - // b = c; - // c = ret; - // } - // return ret; - - // option 2 dp; - if(n==0) return 0; - vector dp(n+1,1); - if(n==1 || n==2) return dp[n]; - dp[0] = 0; - - for(int i=3;i<=n;++i){ - dp[i] = dp[i-1] + dp[i-2] + dp[i-3]; - } - return dp[n]; - } -}; \ No newline at end of file diff --git a/C_plus/114*_FlattenBinaryTreetoLinkedList.cpp b/C_plus/114*_FlattenBinaryTreetoLinkedList.cpp deleted file mode 100644 index 95cd700..0000000 --- a/C_plus/114*_FlattenBinaryTreetoLinkedList.cpp +++ /dev/null @@ -1,82 +0,0 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution -{ -public: - void flatten(TreeNode *root) - { - // option 1 iterative with stack support and new treenode - // if(!root) return; - // TreeNode *ret = new TreeNode(-1), *pre = ret; - // stack sta; - // sta.push(root); - // while(!sta.empty()){ - // TreeNode *node = sta.top(); - // sta.pop(); - // pre->right = node; - // pre->left = nullptr; - // // 因為stack先進後出的性質,會後處理right - // if(node->right) sta.push(node->right); - // if(node->left) sta.push(node->left); - // pre = node; - - // } - // root = ret->right; - - // option 1 version 2 iterative without finction call stack - // while(root){ - // if(root->left){ - // TreeNode * pre = root->left; - // while(pre->right) pre = pre->right; - // pre->right = root->right; - // root->right = root->left; - // root->left = nullptr; - // } - // root = root->right; - // } - - // option 2 recursive - if(!root) return; - - // postorder - flatten(root->left); - flatten(root->right); - // 左右子樹都已經是flatten - - TreeNode *temp = root->right; - root->right = root->left; - root->left = nullptr; - - TreeNode *p = root; - while(p->right) p=p->right; - p->right = temp; - - // option 3 recursive + iterative - // while (root) - // { - // if (root->left) - // { - // flatten(root->left); - // TreeNode *right = root->right; - // root->right = root->left; - // root->left = nullptr; - - // while (root->right) - // { - // root = root->right; - // } - // root->right = right; - // } - // root = root->right; - // } - } -}; \ No newline at end of file diff --git a/C_plus/1143*_LongestCommonSubsequence.cpp b/C_plus/1143*_LongestCommonSubsequence.cpp deleted file mode 100644 index ec0d25c..0000000 --- a/C_plus/1143*_LongestCommonSubsequence.cpp +++ /dev/null @@ -1,85 +0,0 @@ -class Solution -{ -public: - // int dp(string s1, int i, string s2, int j ){ - // // base case - // if(i== s1.size() || j==s2.size()) return 0; - - // // s1[i] 、 s2[j] 都在最長子序列LCS - // if(s1[i] == s2[j]) return 1 + dp(s1,i+1, s2, j+1); - // else{ - - // // s1[i] 、 s2[j] 都不在LCS - // // s2[j] 都不在LCS - // // s1[i] 都不在LCS - - // return max( - // dp(s1, i+1, s2, j+1), - // max( - // dp(s1, i, s2, j+1), - // dp(s1, i+1, s2, j) - // ) - // ); - // } - // } - - int dp(string s1, int i, string s2, int j, vector > &memo) - { - // base case - if (i == s1.size() || j == s2.size()) - return 0; - - // 之前計算過 - if (memo[i][j] != -1) - return memo[i][j]; - - // s1[i] 、 s2[j] 都在最長子序列 - if (s1[i] == s2[j]) - return 1 + dp(s1, i + 1, s2, j + 1, memo); - else - { - // s2[j] 都不在LCS - // s1[i] 都不在LCS - memo[i][j] = max( - dp(s1, i, s2, j + 1, memo), - dp(s1, i + 1, s2, j, memo)); - } - return memo[i][j]; - } - - int longestCommonSubsequence(string text1, string text2) - { - // option 1 brute force time out - - // return dp(text1, 0, text2, 0); - - // option 2 memo pattern time out - // int n = text1.size(), m = text2.size(); - // vector> memo(n , vector(m,-1)); - - // return dp(text1, 0, text2, 0, memo); - - // // option 3 use dp - // // X a c e - // // X 0 0 0 0 - // // a 0 1 1 1 - // // b 0 1 1 1 - // // c 0 1 2 2 - // // d 0 1 2 2 - // // e 0 1 2 3 - int n = text1.size(), m = text2.size(); - vector > dp(n + 1, vector(m + 1, 0)); - - for (int i = 1; i <= n; ++i) - { - for (int j = 1; j <= m; ++j) - { - if (text1[i - 1] == text2[j - 1]) - dp[i][j] = dp[i - 1][j - 1] + 1; - else - dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]); - } - } - return dp[n][m]; - } -}; \ No newline at end of file diff --git a/C_plus/115*_DistinctSubsequences.cpp b/C_plus/115*_DistinctSubsequences.cpp deleted file mode 100644 index 4782490..0000000 --- a/C_plus/115*_DistinctSubsequences.cpp +++ /dev/null @@ -1,34 +0,0 @@ -class Solution -{ -public: - int numDistinct(string s, string t) - { - - // - r a b b b i t - //- 1 1 1 1 1 1 1 1 - //r 0 1 1 1 1 1 1 1 - //a 0 0 1 1 1 1 1 1 - //b 0 0 0 1 2 3 3 3 - //b 0 0 0 0 1 3 3 3 - //i 0 0 0 0 0 0 3 3 - //t 0 0 0 0 0 0 0 3 - - int mod = 1e+9; - int m = s.size(), n = t.size(); - vector > dp(n + 1, vector(m + 1, 0)); - for (int j = 0; j <= m; ++j) - dp[0][j] = 1; - - for (int i = 1; i <= n; ++i) - { - for (int j = 1; j <= m; ++j) - { - if (s[j - 1] == t[i - 1]) - dp[i][j] = (dp[i][j - 1] + dp[i - 1][j - 1]) % mod; - else - dp[i][j] = dp[i][j - 1] % mod; - } - } - return dp[n][m]; - } -}; \ No newline at end of file diff --git a/C_plus/116*_PopulatingNextRightPointersinEachNode.cpp b/C_plus/116*_PopulatingNextRightPointersinEachNode.cpp deleted file mode 100644 index e67100c..0000000 --- a/C_plus/116*_PopulatingNextRightPointersinEachNode.cpp +++ /dev/null @@ -1,67 +0,0 @@ -/* -// Definition for a Node. -class Node { -public: - int val; - Node* left; - Node* right; - Node* next; - - Node() : val(0), left(NULL), right(NULL), next(NULL) {} - - Node(int _val) : val(_val), left(NULL), right(NULL), next(NULL) {} - - Node(int _val, Node* _left, Node* _right, Node* _next) - : val(_val), left(_left), right(_right), next(_next) {} -}; -*/ - -class Solution -{ -public: - void connectTwoNode(Node *node1, Node *node2) - { - if (node1 == nullptr || node2 == nullptr) - return; - - // preorder - node1->next = node2; - - // 連接相同父節點的兩個子節點 - connectTwoNode(node1->left, node1->right); - connectTwoNode(node2->left, node2->right); - - // 連接跨越父節點的兩個子節點 - connectTwoNode(node1->right, node2->left); - } - Node *connect(Node *root) - { - - - // option 1 preorder - if (root == nullptr) return root; - - connectTwoNode(root->left, root->right); - return root; - - - // option 2 level order traverse - if(!root) return nullptr; - queueq; - q.push(root); - while(!q.empty()){ - int size = q.size(); - for(int i = 0; i next = q.front(); - else p->next = nullptr; - - if(p->left) q.push(p->left); - if(p->right) q.push(p->right); - } - } - - return root; - } -}; \ No newline at end of file diff --git a/C_plus/1160_FindWordsThatCanBeFormedbyCharacters.cpp b/C_plus/1160_FindWordsThatCanBeFormedbyCharacters.cpp deleted file mode 100644 index cffa4b8..0000000 --- a/C_plus/1160_FindWordsThatCanBeFormedbyCharacters.cpp +++ /dev/null @@ -1,32 +0,0 @@ -class Solution -{ -public: - bool isGood(string &word, vector dict) - { - - for (char w : word) - { - if (dict[w - 'a'] < 1) - return false; - dict[w - 'a']--; - } - return true; - } - int countCharacters(vector &words, string chars) - { - int ret = 0; - vector dict(26, 0); - for (char c : chars) - dict[c - 'a']++; - - // O(n^2) - for (string word : words) - { - if (isGood(word, dict)) - { - ret += word.size(); - } - } - return ret; - } -}; \ No newline at end of file diff --git a/C_plus/117*_PopulatingNextRightPointersinEachNodeII.cpp b/C_plus/117*_PopulatingNextRightPointersinEachNodeII.cpp deleted file mode 100644 index 5428562..0000000 --- a/C_plus/117*_PopulatingNextRightPointersinEachNodeII.cpp +++ /dev/null @@ -1,47 +0,0 @@ -/* -// Definition for a Node. -class Node { -public: - int val; - Node* left; - Node* right; - Node* next; - - Node() : val(0), left(NULL), right(NULL), next(NULL) {} - - Node(int _val) : val(_val), left(NULL), right(NULL), next(NULL) {} - - Node(int _val, Node* _left, Node* _right, Node* _next) - : val(_val), left(_left), right(_right), next(_next) {} -}; -*/ - -class Solution -{ -public: - Node *connect(Node *root) - { - if (!root) - return nullptr; - queue q; - q.push(root); - while (!q.empty()) - { - int size = q.size(); - for (int i = 0; i < size; ++i) - { - Node *p = q.front(); - q.pop(); - if (i < size - 1) - p->next = q.front(); - else - p->next = nullptr; - if (p->left) - q.push(p->left); - if (p->right) - q.push(p->right); - } - } - return root; - } -}; \ No newline at end of file diff --git a/C_plus/1171*_RemoveZeroSumConsecutiveNodesfromLinkedList.cpp b/C_plus/1171*_RemoveZeroSumConsecutiveNodesfromLinkedList.cpp deleted file mode 100644 index 0f52a9b..0000000 --- a/C_plus/1171*_RemoveZeroSumConsecutiveNodesfromLinkedList.cpp +++ /dev/null @@ -1,63 +0,0 @@ -/** - * Definition for singly-linked list. - * struct ListNode { - * int val; - * ListNode *next; - * ListNode() : val(0), next(nullptr) {} - * ListNode(int x) : val(x), next(nullptr) {} - * ListNode(int x, ListNode *next) : val(x), next(next) {} - * }; - */ -class Solution -{ -public: - ListNode *removeZeroSumSublists(ListNode *head) - { - // option 1 - // Time O(N), one pass - // SpaceO(N), for hashmap - // ListNode *ret = new ListNode(0), *p=ret; - // p->next = head; - // int prefix = 0; - // unordered_map m; - // for(ListNode *i = ret;i;i=i->next){ - // prefix +=i->val; - // if(m.find(prefix)!=m.end()){ - // ListNode *cur = m[prefix]->next; - // ListNode *start = cur; - // int aux = prefix + cur->val; - - // while(cur!=i){ - // m.erase(aux); - // cur=cur->next; - // aux += cur->val; - - // } - // m[prefix]->next = cur->next; - - // } - // else m[prefix] =i; - - // } - // return ret->next; - - // option 2 - // Time O(N), two pass - // SpaceO(N), for hashmap - ListNode *ret = new ListNode(0); - ret->next = head; - unordered_map m; - int prefix = 0; - for (ListNode *i = ret; i; i = i->next) - { - m[prefix += i->val] = i; - } - prefix = 0; - for (ListNode *i = ret; i; i = i->next) - { - // prefix = i->val; - i->next = m[prefix += i->val]->next; - } - return ret->next; - } -}; \ No newline at end of file diff --git a/C_plus/1189_MaximumNumberofBalloons.cpp b/C_plus/1189_MaximumNumberofBalloons.cpp deleted file mode 100644 index 05af4fe..0000000 --- a/C_plus/1189_MaximumNumberofBalloons.cpp +++ /dev/null @@ -1,19 +0,0 @@ -class Solution { -public: - int maxNumberOfBalloons(string text) { - vector his(26,0); - // balloon - for(char c:text) his[c-'a']++; - int ret = 0; - //a:0 , b:1 , - - int b = INT_MAX, l = INT_MAX; - for(int i=0;i<26;++i){ - char c = (char)(i+'a'); - if(c== 'a' || c=='n' || c=='b') b = min(b,his[i]); - else if(c=='o' || c=='l') l = min(l, his[i]); - } - ret = min(l/2, b); - return ret; - } -}; \ No newline at end of file diff --git a/C_plus/118_Pascal'sTriangle.cpp b/C_plus/118_Pascal'sTriangle.cpp deleted file mode 100644 index 96c934c..0000000 --- a/C_plus/118_Pascal'sTriangle.cpp +++ /dev/null @@ -1,24 +0,0 @@ -class Solution -{ -public: - vector > generate(int numRows) - { - vector > ret = {{1}}; - for (int i = 2; i <= numRows; ++i) - { - vector temp = ret[ret.size() - 1]; - int var = temp[0]; - for (int j = 1; j < temp.size(); ++j) - { - int copy = temp[j]; - temp[j] = temp[j] + var; - var = copy; - } - - temp.push_back(1); - ret.push_back(temp); - } - - return ret; - } -}; \ No newline at end of file diff --git a/C_plus/119_Pascal'sTriangleII.cpp b/C_plus/119_Pascal'sTriangleII.cpp deleted file mode 100644 index 91049c3..0000000 --- a/C_plus/119_Pascal'sTriangleII.cpp +++ /dev/null @@ -1,24 +0,0 @@ -class Solution -{ -public: - vector getRow(int rowIndex) - { - vector ret = {1}; - for (int i = 1; i <= rowIndex; ++i) - { - vector temp = ret; - - int var = temp[0]; - for (int j = 1; j < temp.size(); ++j) - { - int copy = temp[j]; - temp[j] = temp[j] + var; - var = copy; - } - ret = temp; - ret.push_back(1); - } - - return ret; - } -}; \ No newline at end of file diff --git a/C_plus/11_ContainerWithMostWater.cpp b/C_plus/11_ContainerWithMostWater.cpp deleted file mode 100644 index 1d45e07..0000000 --- a/C_plus/11_ContainerWithMostWater.cpp +++ /dev/null @@ -1,20 +0,0 @@ -class Solution -{ -public: - int maxArea(vector &height) - { - // two pointer O(n) - int ret = 0; - int l = 0, r = height.size() - 1; - while (l < r) - { - int container = min(height[l], height[r]) * (r - l); - ret = max(ret, container); - if (height[l] > height[r]) - r--; - else - l++; - } - return ret; - } -}; \ No newline at end of file diff --git a/C_plus/12*_IntegerToRoman.cpp b/C_plus/12*_IntegerToRoman.cpp deleted file mode 100644 index feccac7..0000000 --- a/C_plus/12*_IntegerToRoman.cpp +++ /dev/null @@ -1,14 +0,0 @@ -class Solution -{ -public: - string intToRoman(int num) - { - string u[] = {"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"}; - string t[] = {"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"}; - string h[] = {"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"}; - string th[] = {"", "M", "MM", "MMM"}; - - string roman = th[num / 1000] + h[(num % 1000) / 100] + t[(num % 100) / 10] + u[num % 10]; - return roman; - } -}; \ No newline at end of file diff --git a/C_plus/120_Triangle.cpp b/C_plus/120_Triangle.cpp deleted file mode 100644 index b953b02..0000000 --- a/C_plus/120_Triangle.cpp +++ /dev/null @@ -1,38 +0,0 @@ -class Solution -{ -public: - int minimumTotal(vector > &triangle) - { - - int ret = INT_MAX; - int n = triangle.size(); - if (n == 1) - return triangle[0][0]; - - vector > dp(n, vector(n, INT_MAX)); - // 2 = 2 + + + - // 3 4 = 5 6 + + - // 6 5 7 = 11 10 11 - // 4 1 8 3 = 14 11 18 14 - - dp[0][0] = triangle[0][0]; - for (int i = 1; i < n; ++i) - { - for (int j = 0; j <= i; ++j) - { - - if (j == 0) - dp[i][j] = dp[i - 1][j] + triangle[i][j]; - else if (j == i) - dp[i][j] = dp[i - 1][j - 1] + triangle[i][j]; - else - dp[i][j] = min(dp[i - 1][j - 1], dp[i - 1][j]) + triangle[i][j]; - - if (i == n - 1) - ret = min(ret, dp[i][j]); - } - } - - return ret; - } -}; \ No newline at end of file diff --git a/C_plus/121_BestTimeToBuyAndSellStock.cpp b/C_plus/121_BestTimeToBuyAndSellStock.cpp deleted file mode 100644 index b67ee31..0000000 --- a/C_plus/121_BestTimeToBuyAndSellStock.cpp +++ /dev/null @@ -1,72 +0,0 @@ -class Solution -{ -public: - int maxProfit(vector &prices) - { - // option 1 use dp - // 7 1 5 3 6 4 - // 0 0 4 4 5 5 - // -7 -1 -1 -1 -1 -1 - // https://labuladong.gitbook.io/algo/mu-lu-ye/tuan-mie-gu-piao-wen-ti - // base case: - // dp[-1][k][0] = dp[i][0][0] = 0 - // dp[-1][k][1] = dp[i][0][1] = -infinity - - // 状态转移方程: - // dp[i][k][0] = max(dp[i-1][k][0], dp[i-1][k][1] + prices[i]) - // dp[i][k][1] = max(dp[i-1][k][1], dp[i-1][k-1][0] - prices[i]) - - // 7 1 5 3 6 4 - // sell(0) hold(1) - // dp[i][0] = max(dp[i-1][0], dp[i-1][1] + prices[i]); - // dp[i][1] = max(dp[i-1][1], - prices[i]); - //7 0 -7 - //1 0 -1 - //5 4 -1 - //3 4 -1 - //6 5 -1 - //4 5 -1 - - - int n = prices.size(); - vector > dp(n, vector(2, 0)); - for (int i = 0; i < n; ++i) - { - if (i - 1 == -1) - { - dp[i][0] = 0; - dp[i][1] = -prices[i]; - - continue; - } - // 0 沒持有股票,本身就沒持有,或是昨天有持有但賣掉 - dp[i][0] = max(dp[i - 1][0], dp[i - 1][1] + prices[i]); - // 1 持有股票,本身就持有股票,或是昨天還沒有股票今天買 - dp[i][1] = max(dp[i - 1][1], -prices[i]); - } - return dp[n - 1][0]; // 0 沒持有股票,因為最後一定要賣掉 - - // option 1.2 簡化dp - // int n = prices.size(); - // int dp_i_0 = 0, dp_i_1 = INT_MIN; - // 解释:不允许交易的情况下,是不可能持有股票的,用负无穷表示这种不可能。 - // for(int i=0;i > dp(n + 1, vector(5, 0)); - // 0:a 1:e 2:i 3:o 4:u - for (int i = 0; i < 5; ++i) - dp[1][i] = 1; - - for (int i = 1; i < n; ++i) - { - dp[i + 1][0] = (dp[i][1] + dp[i][2] + dp[i][4]) % MOD; - dp[i + 1][1] = (dp[i][0] + dp[i][2]) % MOD; - dp[i + 1][2] = (dp[i][1] + dp[i][3]) % MOD; - dp[i + 1][3] = (dp[i][2]) % MOD; - dp[i + 1][4] = (dp[i][2] + dp[i][3]) % MOD; - } - - for (int i = 0; i < 5; ++i) - ret = (ret + dp[n][i]) % MOD; - - return ret; - } -}; \ No newline at end of file diff --git a/C_plus/122_BestTimeToBuyAndSellStockII.cpp b/C_plus/122_BestTimeToBuyAndSellStockII.cpp deleted file mode 100644 index 73012b6..0000000 --- a/C_plus/122_BestTimeToBuyAndSellStockII.cpp +++ /dev/null @@ -1,51 +0,0 @@ -class Solution -{ -public: - int maxProfit(vector &prices) - { - // option 1 use dp - - // 7 1 5 3 6 4 - // sell(0) hold(1) - // dp[i][0] = max( dp[i-1][0], dp[i-1][1] + prices[i]); - // dp[i][1] = max( dp[i-1][1], dp[i-1][0] - prices[i]); - //7 0 -7 - //1 0 0 - //5 0 0 - //3 0 0 - //6 0 0 - //4 0 0 - - // int n = prices.size(); - // vector> dp(n ,vector(2,0)); - // dp[0][0] = 0; - // dp[0][1] = -prices[0]; - // for(int i=1;i0?profit:0; - // } - // return ret; - } -}; \ No newline at end of file diff --git a/C_plus/123*_BestTimetoBuyandSellStockIII.cpp b/C_plus/123*_BestTimetoBuyandSellStockIII.cpp deleted file mode 100644 index 8bfd30f..0000000 --- a/C_plus/123*_BestTimetoBuyandSellStockIII.cpp +++ /dev/null @@ -1,63 +0,0 @@ -class Solution -{ -public: - int maxProfit(vector &prices) - { - // 原始的动态转移方程,没有可化简的地方 - // dp[i][k][0] = max(dp[i-1][k][0], dp[i-1][k][1] + prices[i]) - // dp[i][k][1] = max(dp[i-1][k][1], dp[i-1][k-1][0] - prices[i]) - - // int n = prices.size(), k=2; - // vector>> dp(n, vector>(k+1, vector(2,0))); - // for(int i=0;i > > dp(n, vector >(k + 1, vector(2, 0))); - for (int i = 0; i < n; ++i) - { - // dp[i][k][0] = max( dp[i-1][k][0], dp[i-1][k][1] + prices[i]); - // dp[i][k][1] = max( dp[i-1][k][1], dp[i-1][k][0] - prices[i]); - for (int t = k; t >= 1; t--) - { - - if (i - 1 == -1) - { - dp[0][t][0] = 0; - dp[0][t][1] = -prices[0]; - continue; - } - dp[i][t][0] = max(dp[i - 1][t][0], dp[i - 1][t][1] + prices[i]); - dp[i][t][1] = max(dp[i - 1][t][1], dp[i - 1][t - 1][0] - prices[i]); - } - } - return dp[n - 1][k][0]; - - // option 2 - // int dp_i10 = 0, dp_i11 = INT_MIN; - // int dp_i20 = 0, dp_i21 = INT_MIN; - // for (int price : prices) { - // dp_i20 = max(dp_i20, dp_i21 + price); - // dp_i21 = max(dp_i21, dp_i10 - price); - // dp_i10 = max(dp_i10, dp_i11 + price); - // dp_i11 = max(dp_i11, -price); - // } - // return dp_i20; - } -}; \ No newline at end of file diff --git a/C_plus/1232_CheckIfItIsaStraightLine.cpp b/C_plus/1232_CheckIfItIsaStraightLine.cpp deleted file mode 100644 index 62e175e..0000000 --- a/C_plus/1232_CheckIfItIsaStraightLine.cpp +++ /dev/null @@ -1,24 +0,0 @@ -/* - * @Author: yuan - * @Date: 2021-05-05 16:59:51 - * @LastEditTime: 2021-05-05 16:59:59 - * @FilePath: /C_plus/1232_CheckIfItIsaStraightLine.cpp - */ -class Solution -{ -public: - bool checkStraightLine(vector > &coordinates) - { - if (coordinates.size() == 2) - return true; - - int m1 = coordinates[1][1] - coordinates[0][1]; - int m2 = coordinates[1][0] - coordinates[0][0]; - for (int i = 2; i < coordinates.size(); ++i) - { - if ((coordinates[i][1] - coordinates[0][1]) * m2 != m1 * (coordinates[i][0] - coordinates[0][0])) - return false; - } - return true; - } -}; \ No newline at end of file diff --git a/C_plus/124*_BinaryTreeMaximumPathSum.cpp b/C_plus/124*_BinaryTreeMaximumPathSum.cpp deleted file mode 100644 index 15da45d..0000000 --- a/C_plus/124*_BinaryTreeMaximumPathSum.cpp +++ /dev/null @@ -1,33 +0,0 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution -{ -public: - int maxPathSum(TreeNode *root) - { - int ret = INT_MIN; - if (!root) - return 0; - maxPath(root, ret); - return ret; - } - - int maxPath(TreeNode *root, int &ret) - { - if (!root) - return 0; - int left = max(0, maxPath(root->left, ret)); - int right = max(0, maxPath(root->right, ret)); - ret = max(ret, left + right + root->val); - return max(left, right) + root->val; - } -}; \ No newline at end of file diff --git a/C_plus/1254_NumberofClosedIslands.cpp b/C_plus/1254_NumberofClosedIslands.cpp deleted file mode 100644 index b8949cf..0000000 --- a/C_plus/1254_NumberofClosedIslands.cpp +++ /dev/null @@ -1,47 +0,0 @@ -class Solution -{ -public: - void dfs(vector > &grid, int i, int j) - { - int n = grid.size(), m = grid[0].size(); - - if (i < 0 || j < 0 || i > n - 1 || j > m - 1) - return; - if (grid[i][j] == 1) - return; - - grid[i][j] = 1; - dfs(grid, i - 1, j); - dfs(grid, i, j - 1); - dfs(grid, i + 1, j); - dfs(grid, i, j + 1); - } - int closedIsland(vector > &grid) - { - int n = grid.size(), m = grid[0].size(); - int ret = 0; - // 先將周圍的島嶼淹掉 - for (int i = 0; i < n; ++i) - { - dfs(grid, i, 0); - dfs(grid, i, m - 1); - } - for (int j = 0; j < m; ++j) - { - dfs(grid, 0, j); - dfs(grid, n - 1, j); - } - - for (int i = 0; i < n; ++i) - { - for (int j = 0; j < m; ++j) - { - if (grid[i][j] == 1) - continue; - dfs(grid, i, j); - ret++; - } - } - return ret; - } -}; \ No newline at end of file diff --git a/C_plus/125_ValidPalindrome.cpp b/C_plus/125_ValidPalindrome.cpp deleted file mode 100644 index 54b16ce..0000000 --- a/C_plus/125_ValidPalindrome.cpp +++ /dev/null @@ -1,38 +0,0 @@ -class Solution -{ -public: - bool isValid(char &c) - { - - if (c >= '0' && c <= '9') - return true; - if (c >= 'a' && c <= 'z') - return true; - if (c >= 'A' && c <= 'Z') - return true; - return false; - } - bool isPalindrome(string s) - { - - int l = 0, r = s.size() - 1; - while (r > l && s[r] == ' ') - r--; - - while (l < r) - { - while (l < r && !isValid(s[l])) - l++; - while (l < r && !isValid(s[r])) - r--; - if (tolower(s[l]) == tolower(s[r])) - { - l++; - r--; - } - else - return false; - } - return true; - } -}; \ No newline at end of file diff --git a/C_plus/1262*_GreatestSumDivisiblebyThree.cpp b/C_plus/1262*_GreatestSumDivisiblebyThree.cpp deleted file mode 100644 index f335650..0000000 --- a/C_plus/1262*_GreatestSumDivisiblebyThree.cpp +++ /dev/null @@ -1,48 +0,0 @@ -class Solution -{ -public: - int maxSumDivThree(vector &nums) - { - - // 當下數字 選或 沒選 都更新 dp - - // dp - // 0 1 2 - // 0 - - - //3 3. -+3 -+3 - //6 9. -+9 -+9 - //5 9 14 -+15 - //1 15 14 10 - //8 18 23 22 - - int n = nums.size(); - vector > dp(n + 1, vector(3, 0)); - dp[0][0] = 0; - dp[0][1] = INT_MIN, dp[0][2] = INT_MIN; - for (int i = 1; i <= n; ++i) - { - // 當下數字 選或 沒選 都更新 dp - if (nums[i - 1] % 3 == 0) - { - dp[i][0] = max(dp[i - 1][0], dp[i - 1][0] + nums[i - 1]); - dp[i][1] = max(dp[i - 1][1], dp[i - 1][1] + nums[i - 1]); - dp[i][2] = max(dp[i - 1][2], dp[i - 1][2] + nums[i - 1]); - } - else if (nums[i - 1] % 3 == 1) - { - // 該數字 餘數為 1 ,餘2的數字 + 餘1的數字 相加會餘0 - dp[i][0] = max(dp[i - 1][0], dp[i - 1][2] + nums[i - 1]); - dp[i][1] = max(dp[i - 1][1], dp[i - 1][0] + nums[i - 1]); - dp[i][2] = max(dp[i - 1][2], dp[i - 1][1] + nums[i - 1]); - } - else - { - // 該數字 餘數為 2 ,餘2的數字 + 餘1 的數字 相加會餘0 - dp[i][0] = max(dp[i - 1][0], dp[i - 1][1] + nums[i - 1]); - dp[i][1] = max(dp[i - 1][1], dp[i - 1][2] + nums[i - 1]); - dp[i][2] = max(dp[i - 1][2], dp[i - 1][0] + nums[i - 1]); - } - } - return dp[n][0]; - } -}; \ No newline at end of file diff --git a/C_plus/127*_WordLadder.cpp b/C_plus/127*_WordLadder.cpp deleted file mode 100644 index 3711975..0000000 --- a/C_plus/127*_WordLadder.cpp +++ /dev/null @@ -1,73 +0,0 @@ -class Solution -{ -public: - int dist(string s, string t) - { - int n = s.size(); - int ret = 0; - for (int i = 0; i < n; ++i) - { - if (s[i] != t[i]) - ret++; - } - return ret; - } - int ladderLength(string beginWord, string endWord, vector &wordList) - { - - // BFS O(n^4) time out - // if(find(wordList.begin(), wordList.end(), endWord) == wordList.end()) return 0; - // int n = wordList.size(); - // queue q; - // q.push(beginWord); - // int step = 1; // 本身也算在長度 - // while(!q.empty()){ - // int size = q.size(); - - // for(int i=0;i wordSet(wordList.begin(), wordList.end()); - if (!wordSet.count(endWord)) - return 0; - queue q{{beginWord}}; - int step = 1; - while (!q.empty()) - { - int size = q.size(); - for (int i = 0; i < size; ++i) - { - string p = q.front(); - q.pop(); - if (p == endWord) - return step; - for (int i = 0; i < p.size(); ++i) - { - string word = p; - for (char ch = 'a'; ch <= 'z'; ++ch) - { - word[i] = ch; - if (wordSet.count(word) && word != p) - { - q.push(word); - wordSet.erase(word); - } - } - } - } - step++; - } - - return 0; - } -}; \ No newline at end of file diff --git a/C_plus/1277_CountSquareSubmatriceswithAllOnes.cpp b/C_plus/1277_CountSquareSubmatriceswithAllOnes.cpp deleted file mode 100644 index 2689b69..0000000 --- a/C_plus/1277_CountSquareSubmatriceswithAllOnes.cpp +++ /dev/null @@ -1,41 +0,0 @@ -class Solution -{ -public: - int countSquares(vector > &matrix) - { - // option 1 dp - // int m = matrix.size(), n=matrix[0].size(); - // vector> dp(m,vector(n,0)); - // for(int i= 0 ;i > dp = matrix; - for (int i = 0; i < m; i++) - { - for (int j = 0; j < n; ++j) - { - if (i && j && dp[i][j]) - dp[i][j] = 1 + min(dp[i - 1][j - 1], min(dp[i - 1][j], dp[i][j - 1])); - - ret += dp[i][j]; - } - } - return ret; - } -}; \ No newline at end of file diff --git a/C_plus/128*_LongestConsecutiveSequence.cpp b/C_plus/128*_LongestConsecutiveSequence.cpp deleted file mode 100644 index 45ae13b..0000000 --- a/C_plus/128*_LongestConsecutiveSequence.cpp +++ /dev/null @@ -1,56 +0,0 @@ -class Solution -{ -public: - int longestConsecutive(vector &nums) - { - // option 1 cheat O(nlogn) - // if(nums.empty()) return 0; - // if(nums.size()==1) return 1; - // sort(nums.begin(), nums.end()); - // set s(nums.begin(), nums.end()); - // vector v(s.begin(), s.end()) ; - // int ret =1, cs=1; - // for(int i=1;i s(nums.begin(), nums.end()); - // int ret = 0; - // for(int n:nums){ - // if(s.find(n)==s.end()) continue; // comment to faster - // s.erase(n); - // int pre = n-1; - // int next = n+1; - // while(s.find(pre)!=s.end()) s.erase(pre--); - // while(s.find(next)!=s.end()) s.erase(next++); - // int count = next-pre-1; - // ret = max(ret, count); - // } - // return ret; - - // option 3 hash table 擴散 - unordered_map m; - int ret = 0; - for (int n : nums) - { - if (m.find(n) != m.end()) - continue; - int left = m.count(n - 1) ? m[n - 1] : 0; - int right = m.count(n + 1) ? m[n + 1] : 0; - int sum = left + right + 1; - cout << sum << endl; - m[n] = sum; - ret = max(ret, sum); - // update hash table - m[n - left] = sum; - m[n + right] = sum; - } - return ret; - } -}; \ No newline at end of file diff --git a/C_plus/1288*_RemoveCoveredIntervals.cpp b/C_plus/1288*_RemoveCoveredIntervals.cpp deleted file mode 100644 index 2fd7ac6..0000000 --- a/C_plus/1288*_RemoveCoveredIntervals.cpp +++ /dev/null @@ -1,52 +0,0 @@ -class Solution -{ -public: - int removeCoveredIntervals(vector > &intervals) - { - // 區間問題,主要技巧有二 - // 1. 排序:按照區間起點做升序排序,如果起點相同則用終點降序排序 - // 2. 畫圖:分析兩區間相對位置有多少種可能。 - - // 計算覆蓋區間有多少個,在用區間總數減去就是剩餘區間數 - - // 兩區間相對位置有三種可能 - // 1. 覆蓋區間 例 [1,6] [2,5] - // 2. 兩區間可以合併,形成一個大區間 例 [1,3] [2,5] => [1,5] - // 3. 兩區間不相交 例 [1,2] [10,12] - - sort(intervals.begin(), intervals.end(), [](vector &a, vector &b) - { - if (a[0] == b[0]) - return a[1] > b[1]; //終點降序排序 - return a[0] < b[0]; // 起點做升序排序 - }); - - // 紀錄合併區間起點及終點 - int start = intervals[0][0], end = intervals[0][1]; - int ret = 0; - for (int i = 1; i < intervals.size(); ++i) - { - vector cur = intervals[i]; - - // 情況一,覆蓋區間 - if ( end >= cur[1]) - { - ret++; - } - // 情況二,兩區間可以合併,形成一個大區間 - else if ( cur[0] <= end && end <= cur[1]) - { - // 因為 cur[0] 大於等於 start,因為有排序 - end = cur[1]; - } - // 情況三,兩區間不相交 - else if (end < cur[0]) - { - // 前進 - start = cur[0]; - end = cur[1]; - } - } - return intervals.size() - ret; - } -}; \ No newline at end of file diff --git a/C_plus/1290_ConvertBinaryNumberinaLinkedListtoInteger.cpp b/C_plus/1290_ConvertBinaryNumberinaLinkedListtoInteger.cpp deleted file mode 100644 index 500d23a..0000000 --- a/C_plus/1290_ConvertBinaryNumberinaLinkedListtoInteger.cpp +++ /dev/null @@ -1,25 +0,0 @@ -/** - * Definition for singly-linked list. - * struct ListNode { - * int val; - * ListNode *next; - * ListNode() : val(0), next(nullptr) {} - * ListNode(int x) : val(x), next(nullptr) {} - * ListNode(int x, ListNode *next) : val(x), next(next) {} - * }; - */ -class Solution -{ -public: - int getDecimalValue(ListNode *head) - { - // option 1 O(N) time, O(1) space - int ret = 0; - for (ListNode *p = head; p; p = p->next) - { - ret <<= 1; - ret += (p->val); - } - return ret; - } -}; \ No newline at end of file diff --git a/C_plus/1295_FindNumberswithEvenNumberofDigits.cpp b/C_plus/1295_FindNumberswithEvenNumberofDigits.cpp deleted file mode 100644 index 5f7553e..0000000 --- a/C_plus/1295_FindNumberswithEvenNumberofDigits.cpp +++ /dev/null @@ -1,44 +0,0 @@ -class Solution -{ -public: - int findNumbers(vector &nums) - { - // option 1 Intuitive - // int ret = 0; - // for(int n:nums){ - // int c= 0; - // while(n){ - // n /=10; - // c++; - // } - // ret +=(c%2==0)?1:0; - // } - // return ret; - - // option 2 tricky ? cheat? - // cause <=10^5 - // 1~9 : 1 , 10~99 : 2 - // 100~999:3 , 1000~9999 : 4 - // 10000~99999:5 , 100000:5 - // int ret = 0; - // for(int n:nums){ - // if( (n>=10 && n<=99) || (n>=1000 && n<=9999) || n==100000) ret++; - // } - // return ret; - - // option 3 log10 - // 1~9、100~999、10000~99999 log10 = [0,1)、[2,3)、[4,5) = int(x) = 0、2、4 - // 10~99、1000~9999、100000 log10 = [1,2)、[3,4)、5 = int(x) = 1、3、5 - // int ret=0; - // for(int n:nums){ - // ret += (int)log10(n)&1; - // } - // return ret; - - // option 4 convert string and compute length - int ret = 0; - for (int n : nums) - ret += (to_string(n).size() % 2 == 0) ? 1 : 0; - return ret; - } -}; \ No newline at end of file diff --git a/C_plus/1299_ReplaceElementswithGreatestElementonRightSide.cpp b/C_plus/1299_ReplaceElementswithGreatestElementonRightSide.cpp deleted file mode 100644 index b18508a..0000000 --- a/C_plus/1299_ReplaceElementswithGreatestElementonRightSide.cpp +++ /dev/null @@ -1,48 +0,0 @@ -class Solution -{ -public: - vector replaceElements(vector &arr) - { - // option 1 reversed traversal - // int n=arr.size(), _max = -1; - // int tmp = arr[n-1]; - // arr[n-1] = _max; - // for(int i=n-2;i>-1;--i){ - // _max = max(tmp, _max); - // tmp = arr[i]; - // arr[i] = _max; - // } - // return arr; - - // option 2 STL stack - stack sta1, sta2; - sta1.push(arr[0]); - for (int i = 1; i < arr.size(); ++i) - { - // cout< sta1.top()) - { - sta1.pop(); - } - sta1.push(arr[i]); - } - sta2.push(-1); - while (!sta1.empty()) - { - sta2.push(sta1.top()); - sta1.pop(); - } - - for (int i = 0; i < arr.size(); ++i) - { - cout << arr[i] << " " << sta2.top() << endl; - if (!sta2.empty() && arr[i] >= sta2.top()) - { - sta2.pop(); - } - arr[i] = sta2.top(); - // sta.pop(); - } - return arr; - } -}; \ No newline at end of file diff --git a/C_plus/129_SumRoottoLeafNumbers.cpp b/C_plus/129_SumRoottoLeafNumbers.cpp deleted file mode 100644 index 1cca262..0000000 --- a/C_plus/129_SumRoottoLeafNumbers.cpp +++ /dev/null @@ -1,50 +0,0 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution -{ -public: - vector > pathSum; - void traverse(TreeNode *root, vector &path) - { - if (!root) - return; - - path.push_back(root->val); - // this is leaf - if (!root->left && !root->right) - { - pathSum.push_back(path); - path.pop_back(); - return; - } - - traverse(root->left, path); - traverse(root->right, path); - path.pop_back(); - } - int sumNumbers(TreeNode *root) - { - vector path; - traverse(root, path); - - int ret = 0; - for (auto path : pathSum) - { - int sum = 0; - for (int p : path) - sum = 10 * sum + p; - - ret += sum; - } - return ret; - } -}; \ No newline at end of file diff --git a/C_plus/130*_SurroundedRegion.cpp b/C_plus/130*_SurroundedRegion.cpp deleted file mode 100644 index 1a0815c..0000000 --- a/C_plus/130*_SurroundedRegion.cpp +++ /dev/null @@ -1,180 +0,0 @@ -class Solution -{ -public: - void solve(vector > &board) - { - // 先從周圍做DFS搜尋將O用別的符號代替,因為這些不受影響,最後再還原 - // 剩下的O代表 沒有與四周相連接的,全部改成X - // 還原步驟1的O - for (int i = 0; i < board.size(); ++i) - { - for (int j = 0; j < board[i].size(); ++j) - { - if ((i == 0 || i == board.size() - 1 || j == 0 || j == board[i].size() - 1) && board[i][j] == 'O') - solveDFS(board, i, j); - } - } - for (auto str : board) - { - for (char c : str) - cout << c << " "; - cout << endl; - } - - for (int i = 0; i < board.size(); ++i) - { - for (int j = 0; j < board[i].size(); ++j) - { - if (board[i][j] == 'O') - board[i][j] = 'X'; - if (board[i][j] == '$') - board[i][j] = 'O'; - } - } - for (auto str : board) - { - for (char c : str) - cout << c << " "; - cout << endl; - } - } - void solveDFS(vector > &board, int i, int j) - { - if (board[i][j] == 'O') - { - board[i][j] = '$'; - if (i > 0 && board[i - 1][j] == 'O') - solveDFS(board, i - 1, j); - if (j < board[i].size() - 1 && board[i][j + 1] == 'O') - solveDFS(board, i, j + 1); - if (i < board.size() - 1 && board[i + 1][j] == 'O') - solveDFS(board, i + 1, j); - if (j > 0 && board[i][j - 1] == 'O') - solveDFS(board, i, j - 1); - } - } -}; - -//option 2 union find -class UF -{ -private: - int count; - vector parent; - vector size; - -public: - UF(int n) - { - count = n; - parent = vector(n); - size = vector(n); - for (int i = 0; i < n; ++i) - { - parent[i] = i; - size[i] = 1; - } - } - - void unionSet(int p, int q) - { - int rootP = find(p); - int rootQ = find(q); - if (rootP == rootQ) - return; - - if (size[rootP] > size[rootQ]) - { - parent[rootQ] = rootP; - size[rootP] += size[rootQ]; - } - else - { - parent[rootP] = rootQ; - size[rootQ] += size[rootP]; - } - count--; - } - // 判斷p q 是否互相連通 - bool connected(int p, int q) - { - int rootP = find(p); - int rootQ = find(q); - return rootQ == rootP; - } - // 返回 節點 x 的根節點 - int find(int x) - { - while (parent[x] != x) - { - // 進行路徑壓縮 - parent[x] = parent[parent[x]]; - x = parent[x]; - } - return x; - } - int length() - { - return count; - } -}; -class Solution -{ -public: - void solve(vector > &board) - { - if (board.size() == 0) - return; - - int m = board.size(), n = board[0].size(); - - UF *uf = new UF(m * n + 1); - int dummy = m * n; - - // 首行與末行的O與dummy 連通 - for (int i = 0; i < m; ++i) - { - if (board[i][0] == 'O') - uf->unionSet(i * n, dummy); - if (board[i][n - 1] == 'O') - uf->unionSet(i * n + n - 1, dummy); - } - - // 首列與末列的O與dummy 連通 - for (int j = 0; j < n; ++j) - { - if (board[0][j] == 'O') - uf->unionSet(j, dummy); - if (board[m - 1][j] == 'O') - uf->unionSet(n * (m - 1) + j, dummy); - } - - vector > action = {{1, 0}, {0, 1}, {0, -1}, {-1, 0}}; - for (int i = 1; i < m - 1; ++i) - { - for (int j = 1; j < n - 1; ++j) - { - if (board[i][j] == 'O') - { - // 将此 O 与上下左右的 O 连通 - for (int k = 0; k < 4; ++k) - { - int x = i + action[k][0]; - int y = j + action[k][1]; - if (board[x][y] == 'O') - uf->unionSet(x * n + y, i * n + j); - } - } - } - } - // 所有不和 dummy 连通的 O,都要被替换 - for (int i = 1; i < m - 1; i++) - { - for (int j = 1; j < n - 1; j++) - { - if (!uf->connected(dummy, i * n + j)) - board[i][j] = 'X'; - } - } - } -}; \ No newline at end of file diff --git a/C_plus/1306_JumpGameIII.cpp b/C_plus/1306_JumpGameIII.cpp deleted file mode 100644 index 92e9545..0000000 --- a/C_plus/1306_JumpGameIII.cpp +++ /dev/null @@ -1,59 +0,0 @@ -class Solution -{ -public: - void backtracking(vector &arr, int start, vector &visited) - { - - int n = arr.size(); - - if (start < 0 || start > n - 1 || visited[start]) - return; - visited[start] = true; - - if (arr[start] == 0) - return; - backtracking(arr, start + arr[start], visited); - backtracking(arr, start - arr[start], visited); - } - bool canReach(vector &arr, int start) - { - // DFS - // int n = arr.size(); - // vector visited(n, false); - // backtracking(arr, start, visited); - // for(int i=0;i q; - int n = arr.size(); - vector visited(n, false); - - q.push(start); - visited[start] = true; - while (!q.empty()) - { - int size = q.size(); - for (int i = 0; i < size; ++i) - { - int p = q.front(); - q.pop(); - if (arr[p] == 0) - return true; - if (p + arr[p] < n && visited[p + arr[p]] == false) - { - q.push(p + arr[p]); - visited[p + arr[p]] = true; - } - if (p - arr[p] > -1 && visited[p - arr[p]] == false) - { - q.push(p - arr[p]); - visited[p - arr[p]] = true; - } - } - } - return false; - } -}; \ No newline at end of file diff --git a/C_plus/131*_PalindromePartitioning.cpp b/C_plus/131*_PalindromePartitioning.cpp deleted file mode 100644 index a4257c5..0000000 --- a/C_plus/131*_PalindromePartitioning.cpp +++ /dev/null @@ -1,31 +0,0 @@ -class Solution { -public: - bool isPalindrome(string v, int l, int r ){ - while(l<=r){ - if(v[l]!=v[r]) return false; - l++; - r--; - } - return true; - } - void helper(string s, int start , vector out, vector> &ret){ - - if(start>=s.size()){ - ret.push_back(out); - return ; - } - - for(int i=start;i> partition(string s) { - vector> ret; - vector out; - helper(s, 0, out, ret); - return ret; - } -}; \ No newline at end of file diff --git a/C_plus/1312*_MinimumInsertionStepstoMakeaStringPalindrome.cpp b/C_plus/1312*_MinimumInsertionStepstoMakeaStringPalindrome.cpp deleted file mode 100644 index 3b3a5ad..0000000 --- a/C_plus/1312*_MinimumInsertionStepstoMakeaStringPalindrome.cpp +++ /dev/null @@ -1,53 +0,0 @@ -class Solution -{ -public: - int minInsertions(string s) - { - - /* - if (s[i] == s[j]) { - dp[i][j] = dp[i + 1][j - 1]; - } - else if(s[i] != s[j]){ - // 把 s[j] 插到 s[i] 右邊,同時把 s[i] 插到 s[j] 右邊 - dp[i][j] = dp[i + 1][j - 1] + 2; - - 做選擇,先將 s[i..j-1] 或者 s[i+1..j] 變成回文串 - dp[i][j] = min(dp[i + 1][j], dp[i][j - 1]) + 1; - } - 假設已經算出 dp[i+1][j-1] ,即已經知道 s[i+1...j-1] 成為回文的最小插入次數, - 那麼也可以認為s[i+1..j-1]已經是回文字串, - 所以通過 dp[i+1][j-1]推導 dp[i][j] 的關鍵就是在s[i] s[j]兩字符 - - 如果 s[i] = s[j] 不需要插入,只要將指標前進到 i+1 j-1 即可 - 如果s[i] != s[j] ,分成兩種狀況,s[j] 插到 s[i] 右邊 ,同時把s[i] 插到 s[j] 右邊,那建構出來一定是回文字串。 - if(s[i] != s[j] ) dp[i][j] = dp[i + 1][j - 1] + 2; - 但是這種情況只需插入一個字符即可,"xaaaaa" 或是 "aaaaax" 當 i=0, j=5,所以當s[i] != s[j]時,無腦插入兩次可以變為回文字串但未必是插入最少。 - 最佳插入方案應該是, - step1 s[i..j-1] 或是 s[i+1..j]變為回文字串,誰變成回文字串插入次數少就選誰,min(dp[i][j-1], dp[i+1][j] )+1; 。 - step2 根據 step1 假如將s[i+1..j] 變為回文,那麼一定可以在s[i+1..j]右邊插入一個字符s[i],一定可以將s[i..j]變成回文,同理s[i..j-1] 在左邊插入s[j]必定可以將s[i..j]變成回文。 - dp[i][j] = 3,即 s[i..j] 經過 最小插入次數3 可以成為回文 - */ - int n = s.size(); - vector > dp(n, vector(n, 0)); - // initalize dp, base case i==j 代表 i..j 已是回文 - for (int i = 0; i < n; ++i) - dp[i][i] = 0; - - for (int i = n - 1; i > -1; --i) - { - for (int j = i + 1; j < n; ++j) - { - - if (s[i] == s[j]) - dp[i][j] = dp[i + 1][j - 1]; - else if (s[i] != s[j]) - { - dp[i][j] = min(dp[i + 1][j], dp[i][j - 1]) + 1; - } - } - } - - return dp[0][n - 1]; - } -}; \ No newline at end of file diff --git a/C_plus/1323_Maximum69Number.cpp b/C_plus/1323_Maximum69Number.cpp deleted file mode 100644 index 2068903..0000000 --- a/C_plus/1323_Maximum69Number.cpp +++ /dev/null @@ -1,39 +0,0 @@ -class Solution -{ -public: - int maximum69Number(int num) - { - // option 1 - // 從左邊開始第一個六換成九。 - // int ret = 0; - // while(num){ - // ret = 10*ret + (num%10); - // num /=10; - // } - // bool f = true; - // int i=-1; - // int n = ret; - // int ans = 0; - // while(n){ - // if((n%10)==6 && f){ - // f = false; - // ans = 10*ans +9; - // } - // else ans = 10*ans + (n%10); - // n/=10; - // } - // return ans; - - // option 2 - string s = to_string(num); - for (int i = 0; i < s.size(); ++i) - { - if (s[i] == '6') - { - s[i] = '9'; - return stoi(s); - } - } - return num; - } -}; \ No newline at end of file diff --git a/C_plus/133*_CloneGraph.cpp b/C_plus/133*_CloneGraph.cpp deleted file mode 100644 index a9f8a97..0000000 --- a/C_plus/133*_CloneGraph.cpp +++ /dev/null @@ -1,50 +0,0 @@ -/* -// Definition for a Node. -class Node { -public: - int val; - vector neighbors; - Node() { - val = 0; - neighbors = vector(); - } - Node(int _val) { - val = _val; - neighbors = vector(); - } - Node(int _val, vector _neighbors) { - val = _val; - neighbors = _neighbors; - } -}; -*/ - -class Solution -{ -public: - unordered_map m; - Node *dfs(Node *node) - { - - if (!node) - return nullptr; - if (m.count(node)) - return m[node]; - - Node *clone = new Node(node->val); - m[node] = clone; - vector childrend; - for (Node *child : node->neighbors) - { - childrend.push_back(dfs(child)); - } - clone->neighbors = childrend; - - return clone; - } - Node *cloneGraph(Node *node) - { - //DFS - return dfs(node); - } -}; \ No newline at end of file diff --git a/C_plus/1338_ReduceArraySizetoTheHalf.cpp b/C_plus/1338_ReduceArraySizetoTheHalf.cpp deleted file mode 100644 index c18fc1e..0000000 --- a/C_plus/1338_ReduceArraySizetoTheHalf.cpp +++ /dev/null @@ -1,34 +0,0 @@ -class Solution -{ -public: - int minSetSize(vector &arr) - { - - // option 1 STL O(m log m) time and O(m) time , m is the number of unique numbers - map m; - int size = arr.size(); - priority_queue, vector >, less > > pq; - - for (int a : arr) - { - m[a]++; - } - for (auto mm : m) - { - pq.push(make_pair(mm.second, mm.first)); - } - - int count = 0, ret = 0; - while (!pq.empty()) - { - if (count >= size / 2) - break; - pair p = pq.top(); - count += p.first; - ret++; - pq.pop(); - } - - return ret; - } -}; \ No newline at end of file diff --git a/C_plus/1339*_MaximumProductofSplittedBinaryTree.cpp b/C_plus/1339*_MaximumProductofSplittedBinaryTree.cpp deleted file mode 100644 index b54a444..0000000 --- a/C_plus/1339*_MaximumProductofSplittedBinaryTree.cpp +++ /dev/null @@ -1,34 +0,0 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution -{ -public: - long res = 0; - const int mod = 1e9 + 7; - int sum(TreeNode *root, long total) - { - if (!root) - return 0; - int s1 = sum(root->left, total); - int s2 = sum(root->right, total); - int s = s1 + s2 + root->val; - res = max(res, s * (total - s)); - return s; - } - int maxProduct(TreeNode *root) - { - // - int total = sum(root, 0); - sum(root, total); - return res % mod; - } -}; \ No newline at end of file diff --git a/C_plus/1346_CheckIfNandItsDoubleExist.cpp b/C_plus/1346_CheckIfNandItsDoubleExist.cpp deleted file mode 100644 index 34d677c..0000000 --- a/C_plus/1346_CheckIfNandItsDoubleExist.cpp +++ /dev/null @@ -1,28 +0,0 @@ -class Solution -{ -public: - bool checkIfExist(vector &arr) - { - // option1 O(nlogn) - // set s; - // for(int a:arr){ - // if(s.find(a)!=s.end()) return true; - // if(a%2==0 ) { - // s.insert(a/2); - // } - // s.insert(a*2); - - // } - // return false; - - // option1 O(nlogn) - set s; - for (int n : arr) - { - if (s.find(n * 2) != s.end() || (n % 2 == 0 && s.find(n / 2) != s.end())) - return true; - s.insert(n); - } - return false; - } -}; \ No newline at end of file diff --git a/C_plus/134_GasStation.cpp b/C_plus/134_GasStation.cpp deleted file mode 100644 index 8b89d0e..0000000 --- a/C_plus/134_GasStation.cpp +++ /dev/null @@ -1,81 +0,0 @@ -class Solution -{ -public: - int canCompleteCircuit(vector &gas, vector &cost) - { - - // option 1 brute force O(n^2) - // int n = gas.size(); - // vector ret(n, 0); - - // for(int i=0;i< n ;++i){ - // int cur = gas[i]; - // for(int j=i+1;j<=n+i;++j){ - // cur -=cost[(j-1)%n] ; - - // if(cur<0){ - // cur = -1; - // break; - // } - // cur += gas[j%n]; - // } - // ret[i] = cur; - // } - - // int idx = -1, val = -1; - // for(int i = 0;i val){ - // idx = i; - // val = ret[i]; - // } - // } - // return idx; - - // option 2 O(n) - // 剪枝 - // 1 2 3 4 5 - // 3 4 5 1 2 - //sum -2 -4 -6 -3 0 將0作為起點在油箱變化量 - // 將sum 最低點作為起點,往上平移 - // 4 2 0 3 6 - // 最低點 index = 2+1 就是出發點 - // 找 sum 陣列中最小值的索引 +1 - // int n = gas.size(), sum = 0; - // int minSum = INT_MAX; - // int start = 0; - // for(int i=0;i &ratings) - { - - // 1 0 2 - //l 1 1 2 - //r 2 1 2 - - // 1 2 2 - // 1 2 1 - // - int n = ratings.size(); - vector nums(n, 1); - for (int i = 0; i < n - 1; i++) - { - if (ratings[i + 1] > ratings[i]) - nums[i + 1] = nums[i] + 1; - } - - for (int i = n - 1; i > 0; --i) - { - if (ratings[i - 1] > ratings[i]) - nums[i - 1] = max(nums[i - 1], nums[i] + 1); - } - int ret = 0; - for (int n : nums) - ret += n; - return ret; - } -}; \ No newline at end of file diff --git a/C_plus/1356_SortIntegersbyTheNumberof1Bits.cpp b/C_plus/1356_SortIntegersbyTheNumberof1Bits.cpp deleted file mode 100644 index 11f3574..0000000 --- a/C_plus/1356_SortIntegersbyTheNumberof1Bits.cpp +++ /dev/null @@ -1,27 +0,0 @@ -class Solution -{ -public: - static int count(int n) - { - int ret = 0; - while (n) - { - ret++; - n = n & (n - 1); - } - return ret; - } - static bool cmp(int a, int b) - { - int ca = count(a), cb = count(b); - if (ca == cb) - return a < b; - return ca < cb; - } - vector sortByBits(vector &arr) - { - // O(nlogn) time and O(1) time - sort(arr.begin(), arr.end(), cmp); - return arr; - } -}; \ No newline at end of file diff --git a/C_plus/1365_HowManyNumbersAreSmallerThantheCurrentNumber.cpp b/C_plus/1365_HowManyNumbersAreSmallerThantheCurrentNumber.cpp deleted file mode 100644 index ab0821f..0000000 --- a/C_plus/1365_HowManyNumbersAreSmallerThantheCurrentNumber.cpp +++ /dev/null @@ -1,42 +0,0 @@ -class Solution -{ -public: - vector smallerNumbersThanCurrent(vector &nums) - { - // option 1 O(n^2) brute force - // int n= nums.size(); - // vector ret(n,0); - // for(int i=0;i vec(101, 0); - vector ret(n, 0); - int _min = 100, _max = 0; - for (int m : nums) - { - vec[m]++; - _min = min(m, _min); - _max = max(m, _max); - } - int total = 0, pre = 0; - for (int i = _min; i <= _max; ++i) - { - pre = vec[i]; - vec[i] = total; - total += pre; - } - - for (int i = 0; i < n; ++i) - { - ret[i] = vec[nums[i]]; - } - return ret; - } -}; \ No newline at end of file diff --git a/C_plus/136_SingleNumber.cpp b/C_plus/136_SingleNumber.cpp deleted file mode 100644 index 43e25b4..0000000 --- a/C_plus/136_SingleNumber.cpp +++ /dev/null @@ -1,25 +0,0 @@ -class Solution -{ -public: - int singleNumber(vector &nums) - { - // option 1 bit manipulation - // a ^ a = 0 a ^ 0 = a,^有交換率,成對的數字變成0 - // int ret = 0; - // for(int n:nums) ret^= n; - // return ret; - - // optnio 2 general case - int ret = 0; - for (int i = 0; i < 32; ++i) - { - int sum = 0; - for (int n : nums) - { - sum += (n >> i) & 1; - } - ret += (sum % 2) << i; - } - return ret; - } -}; \ No newline at end of file diff --git a/C_plus/137*_SingleNumberII.cpp b/C_plus/137*_SingleNumberII.cpp deleted file mode 100644 index f5f020f..0000000 --- a/C_plus/137*_SingleNumberII.cpp +++ /dev/null @@ -1,33 +0,0 @@ -class Solution -{ -public: - int singleNumber(vector &nums) - { - - // option 0 cheap - // unordered_map dict; - // for(int n :nums) dict[n]++; - - // for(int n :nums){ - // if(dict[n]==1) return n; - // } - // return -1; - - // option 1 Bit manipulation O(n) time and O(1) space - // 按照位元 ,每位取為1總和 %3 ,即為答案 - - int ret = 0; - for (int i = 0; i < 32; ++i) - { - int sum = 0; - for (int j = 0; j < nums.size(); ++j) - { - sum += (nums[j] >> i) & 1; - } - - ret += (sum % 3) << i; - } - - return ret; - } -}; \ No newline at end of file diff --git a/C_plus/1373*_MaximumSumBSTinBinaryTree.cpp b/C_plus/1373*_MaximumSumBSTinBinaryTree.cpp deleted file mode 100644 index 28021e8..0000000 --- a/C_plus/1373*_MaximumSumBSTinBinaryTree.cpp +++ /dev/null @@ -1,64 +0,0 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution -{ -private: - int maxSum = 0; - struct str - { - bool isBST; - int minVal; - int maxVal; - int sum; - }; - -public: - str traverse(TreeNode *root) - { - if (!root) - { - return {true, INT_MAX, INT_MIN, 0}; - } - - // 遞迴計算左右子樹 - str left = traverse(root->left); - str right = traverse(root->right); - - // postorder - str ret; - if (left.isBST == true && right.isBST == true && root->val > left.maxVal && root->val < right.minVal) - { - - ret.isBST = true; - ret.minVal = min(left.minVal, root->val); - ret.maxVal = max(right.maxVal, root->val); - - ret.sum = left.sum + right.sum + root->val; - - maxSum = max(maxSum, ret.sum); - } - else - { - ret.isBST = false; - } - return ret; - } - int maxSumBST(TreeNode *root) - { - // 1. 左右子樹是否為BST,如果其一不合法,那我本身也不合法 - // 2. 如果左右子樹都合法,還得看看加上自己是否合法,所以得找左子樹最大值和右子樹最小值 - // 3. 左右子樹節點值之和 - - traverse(root); - return maxSum; - } -}; \ No newline at end of file diff --git a/C_plus/138*_CopyListwithRandomPointer.cpp b/C_plus/138*_CopyListwithRandomPointer.cpp deleted file mode 100644 index 797a6f5..0000000 --- a/C_plus/138*_CopyListwithRandomPointer.cpp +++ /dev/null @@ -1,43 +0,0 @@ -/* -// Definition for a Node. -class Node { -public: - int val; - Node* next; - Node* random; - - Node(int _val) { - val = _val; - next = NULL; - random = NULL; - } -}; -*/ - -class Solution -{ -public: - Node *copyRandomList(Node *head) - { - Node *ret = new Node(-1), *p = ret; - map m; // old list mapping new list - Node *cur = head; - while (cur) - { - p->next = new Node(cur->val); - m[cur] = p->next; - p = p->next; - cur = cur->next; - } - - // for(p=ret->next;p;p=p->next) cout<val<random = m[cur->random]; - cur = cur->next; - } - return ret->next; - } -}; \ No newline at end of file diff --git a/C_plus/139*_WordBreak.cpp b/C_plus/139*_WordBreak.cpp deleted file mode 100644 index 041f35c..0000000 --- a/C_plus/139*_WordBreak.cpp +++ /dev/null @@ -1,47 +0,0 @@ -class Solution -{ -public: - unordered_map memo; - bool check(string &s, unordered_set &words) - { - if (words.count(s)) - return true; - if (memo.count(s)) - return memo[s]; - for (int i = 1; i <= s.size(); ++i) - { - string left = s.substr(0, i); - string right = s.substr(i, s.size()); - if (words.count(left) && check(right, words)) - return memo[s] = true; - } - return memo[s] = false; - } - bool wordBreak(string s, vector &wordDict) - { - // option 0 brute force => time out - // option 1 brute force + memo - // unordered_set words(wordDict.begin(), wordDict.end()); - // return check(s, words); - - // option 2 dp - // l e e t c o d e - // t f f f f f f f f - // t f f f t f f f t - unordered_set words(wordDict.begin(), wordDict.end()); - vector dp(s.size() + 1, false); - dp[0] = true; - for (int i = 0; i < dp.size(); ++i) - { - for (int j = 0; j < i; ++j) - { - if (dp[j] && words.count(s.substr(j, i - j))) - { - dp[i] = true; - break; - } - } - } - return dp.back(); - } -}; \ No newline at end of file diff --git a/C_plus/13_RomanToInteger.cpp b/C_plus/13_RomanToInteger.cpp deleted file mode 100644 index b0315ee..0000000 --- a/C_plus/13_RomanToInteger.cpp +++ /dev/null @@ -1,19 +0,0 @@ -class Solution -{ -public: - int romanToInt(string s) - { - map dict = {{'I', 1}, {'V', 5}, {'X', 10}, {'L', 50}, {'C', 100}, {'D', 500}, {'M', 1000}}; - - int ret = dict[s[0]]; - for (int i = 1; i < s.size(); ++i) - { - if (dict[s[i - 1]] < dict[s[i]]) - ret += (dict[s[i]] - 2 * dict[s[i - 1]]); - else if (dict[i - 1] >= dict[i]) - ret += dict[s[i]]; - } - - return ret; - } -}; \ No newline at end of file diff --git a/C_plus/140*_WordBreakII.cpp b/C_plus/140*_WordBreakII.cpp deleted file mode 100644 index 1ca781c..0000000 --- a/C_plus/140*_WordBreakII.cpp +++ /dev/null @@ -1,30 +0,0 @@ -class Solution -{ -public: - unordered_map > memo; - vector helper(string s, vector words) - { - if (memo.count(s)) - return memo[s]; - if (s.empty()) - return {""}; - - vector ret; - for (string word : words) - { - if (s.substr(0, word.size()) != word) - continue; - vector rem = helper(s.substr(word.size()), words); - for (string str : rem) - { - ret.push_back(word + (str.empty() ? "" : " ") + str); - } - } - return memo[s] = ret; - } - vector wordBreak(string s, vector &wordDict) - { - // recursive - return helper(s, wordDict); - } -}; \ No newline at end of file diff --git a/C_plus/141_LinkedListCycle.cpp b/C_plus/141_LinkedListCycle.cpp deleted file mode 100644 index 0f0a0d9..0000000 --- a/C_plus/141_LinkedListCycle.cpp +++ /dev/null @@ -1,38 +0,0 @@ -/** - * Definition for singly-linked list. - * struct ListNode { - * int val; - * ListNode *next; - * ListNode(int x) : val(x), next(NULL) {} - * }; - */ -class Solution -{ -public: - bool hasCycle(ListNode *head) - { - // two pointer ,slow fast point 用於linked list是否包含環, left right pointer用於數組 二元搜尋法 - // option 1 two pointer , slow fast - ListNode *slow, *fast = head; - while (fast && fast->next) - { - - slow = slow->next; - fast = fast->next->next; - if (slow == fast) - return true; - } - return false; - - // option 2 - // set s; - - // for(ListNode *cur = head;cur;cur=cur->next){ - // if(s.find(cur)!= s.end()) return true; - - // s.insert(cur); - // } - - // return false; - } -}; \ No newline at end of file diff --git a/C_plus/142*_LinkedListCycleII.cpp b/C_plus/142*_LinkedListCycleII.cpp deleted file mode 100644 index 695108e..0000000 --- a/C_plus/142*_LinkedListCycleII.cpp +++ /dev/null @@ -1,40 +0,0 @@ -/** - * Definition for singly-linked list. - * struct ListNode { - * int val; - * ListNode *next; - * ListNode(int x) : val(x), next(NULL) {} - * }; - */ -class Solution -{ -public: - ListNode *detectCycle(ListNode *head) - { - - // option 1 - // 1. 快慢指標判斷有無交點 - // 2. 若無交點,返回nullptr - // 3. 有交點,此時fast從相遇點走到下次相遇點距離,等於slow從起點走到下次相遇點。 - ListNode *slow = head, *fast = head; - - while (fast && fast->next) - { - slow = slow->next; - fast = fast->next->next; - if (fast == slow) - break; // detect cycle - } - // fast遇到空指標,代表沒有環 - if (fast == nullptr || fast->next == nullptr) - return nullptr; - - slow = head; - while (slow != fast) - { - fast = fast->next; - slow = slow->next; - } - return slow; - } -}; \ No newline at end of file diff --git a/C_plus/143*_ReorderList.cpp b/C_plus/143*_ReorderList.cpp deleted file mode 100644 index 4b991cc..0000000 --- a/C_plus/143*_ReorderList.cpp +++ /dev/null @@ -1,75 +0,0 @@ -/** - * Definition for singly-linked list. - * struct ListNode { - * int val; - * ListNode *next; - * ListNode() : val(0), next(nullptr) {} - * ListNode(int x) : val(x), next(nullptr) {} - * ListNode(int x, ListNode *next) : val(x), next(next) {} - * }; - */ -class Solution -{ -public: - void reorderList(ListNode *head) - { - // 1. slow-fast to find middle point - // 2. reverse the scond linked list - // 3. merge list 1 and list 2 - if (!head || !head->next) - return; - - ListNode *slow = head, *fast = head, *pre = nullptr; - - while (fast && fast->next) - { - fast = fast->next->next; - pre = slow; - slow = slow->next; - } - pre->next = nullptr; - - for (ListNode *p = head; p; p = p->next) - cout << p->val << " "; - cout << endl; - for (ListNode *p = slow; p; p = p->next) - cout << p->val << " "; - cout << endl; - - // 2. reverse linked list - pre = nullptr; - ListNode *cur = slow, *post = slow->next; - while (post) - { - cur->next = pre; - pre = cur; - cur = post; - post = post->next; - } - - cur->next = pre; - - // 3. merge tow linked list - ListNode *s1 = head->next, *s2 = cur; - ListNode *ret = head; - // ListNode *merge = new ListNode(0), *ret = merge; - - while (s1 || s2) - { - - if (s2) - { - ret->next = s2; - s2 = s2->next; - ret = ret->next; - } - - if (s1) - { - ret->next = s1; - s1 = s1->next; - ret = ret->next; - } - } - } -}; \ No newline at end of file diff --git a/C_plus/1448*_CountGoodNodesinBinaryTree.cpp b/C_plus/1448*_CountGoodNodesinBinaryTree.cpp deleted file mode 100644 index eeba3a6..0000000 --- a/C_plus/1448*_CountGoodNodesinBinaryTree.cpp +++ /dev/null @@ -1,35 +0,0 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution -{ -public: - int ans = 0; - void traverse(TreeNode *root, int mx) - { - if (!root) - return; - - // preorder - if (root->val >= mx) - { - ans++; - mx = root->val; - } - traverse(root->left, mx); - traverse(root->right, mx); - } - int goodNodes(TreeNode *root) - { - traverse(root, INT_MIN); - return ans; - } -}; \ No newline at end of file diff --git a/C_plus/144_BinaryTreePreorderTraversal.cpp b/C_plus/144_BinaryTreePreorderTraversal.cpp deleted file mode 100644 index 1c6158e..0000000 --- a/C_plus/144_BinaryTreePreorderTraversal.cpp +++ /dev/null @@ -1,33 +0,0 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution -{ -public: - void preorder(TreeNode *root, vector &ret) - { - if (!root) - return; - ret.push_back(root->val); // V - preorder(root->left, ret); // L - preorder(root->right, ret); // R - } - vector preorderTraversal(TreeNode *root) - { - // option 1 recursive O(n) space - vector ret; - preorder(root, ret); - return ret; - - // option 2 non-recursive O(n) space - // option 3 Morris Traversal O(1) space - } -}; \ No newline at end of file diff --git a/C_plus/145_BinaryTreePostorderTraversal.cpp b/C_plus/145_BinaryTreePostorderTraversal.cpp deleted file mode 100644 index acd4e84..0000000 --- a/C_plus/145_BinaryTreePostorderTraversal.cpp +++ /dev/null @@ -1,36 +0,0 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution -{ -public: - void postorder(TreeNode *root, vector &ret) - { - - if (root) - { - postorder(root->left, ret); // L - postorder(root->right, ret); // R - ret.push_back(root->val); // V - } - } - vector postorderTraversal(TreeNode *root) - { - // option 1 recursive O(n) space - vector ret; - postorder(root, ret); - return ret; - - // option 2 non-recursive O(n) space - // option 3 Morris Traversal O(1) space - - } -}; \ No newline at end of file diff --git a/C_plus/146*_LRUCache.cpp b/C_plus/146*_LRUCache.cpp deleted file mode 100644 index f553d9e..0000000 --- a/C_plus/146*_LRUCache.cpp +++ /dev/null @@ -1,185 +0,0 @@ -class LRUCache -{ -private: - list > l; - unordered_map >::iterator> m; - int cap; - -public: - LRUCache(int capacity) - { - cap = capacity; - } - - int get(int key) - { - // cout<<"get"<second); - // cout<<"----splice--"<second->second; - } - - void put(int key, int value) - { - auto it = m.find(key); - if (it != m.end()) - l.erase(it->second); - l.push_front(make_pair(key, value)); - m[key] = l.begin(); - if (m.size() > cap) - { - int k = l.rbegin()->first; - l.pop_back(); - m.erase(k); - } - } -}; - -/** - * Your LRUCache object will be instantiated and called as such: - * LRUCache* obj = new LRUCache(capacity); - * int param_1 = obj->get(key); - * obj->put(key,value); - */ - -class Node -{ -public: - int key, val; - Node *next, *prev; - Node(int k, int v) : key(k), val(v) {} -}; -class DoubleList -{ -private: - Node *head, *tail; - int size; - -public: - DoubleList() - { - head = new Node(0, 0); - tail = new Node(0, 0); - head->next = tail; - tail->prev = head; - size = 0; - } - void addLast(Node *x) - { - x->prev = tail->prev; - x->next = tail; - tail->prev->next = x; - tail->prev = x; - size++; - - // Node *t = tail->prev; - // x->next = tail; - // tail->prev = x; - // x->prev = t; - // t->next = x; - // size++; - } - // 由於是雙向鏈接串列且給定目標Node節點,O(1) - void remove(Node *x) - { - x->prev->next = x->next; - x->next->prev = x->prev; - size--; - } - Node *removeFirst() - { - if (head->next == tail) - return nullptr; - Node *first = head->next; - remove(first); - return first; - } - int Getsize() - { - return size; - } -}; -class LRUCache -{ -private: - unordered_map mp; - DoubleList cache; - int cap; - // 將key 提升為最常使用 - void makeRecently(int key) - { - Node *x = mp[key]; - // 從鏈接串列刪除該節點 - cache.remove(x); - // 重新插到串列尾部 - cache.addLast(x); - } - void addRecently(int key, int val) - { - Node *x = new Node(key, val); - // 鏈接串列尾部就是最近使用的元素 - cache.addLast(x); - mp[key] = x; - } - void deleteKey(int key) - { - Node *x = mp[key]; - cache.remove(x); - mp.erase(key); - } - void removeLeastRecently() - { - Node *deleteNode = cache.removeFirst(); - int deleteKey = deleteNode->key; - mp.erase(deleteKey); - } - -public: - LRUCache(int capacity) - { - cap = capacity; - } - - int get(int key) - { - // 每次拜訪需要將這元素變為最近使用,也就是說cache要支持任意位置元素插入與刪除 - // hash 搜詢快,但是其資料無順序 - // double linked list 插入刪除快,但搜尋慢。 - if (!mp.count(key)) - return -1; - makeRecently(key); - return mp[key]->val; - } - - void put(int key, int value) - { - if (mp.count(key)) - { - // 刪除舊資料 - deleteKey(key); - // 新插入資料為最近使用的資料 - addRecently(key, value); - return; - } - - if (cap == cache.Getsize()) - { - removeLeastRecently(); - } - // 添加最近使用的元素 - addRecently(key, value); - } -}; - -/** - * Your LRUCache object will be instantiated and called as such: - * LRUCache* obj = new LRUCache(capacity); - * int param_1 = obj->get(key); - * obj->put(key,value); - */ \ No newline at end of file diff --git a/C_plus/147*_InsertuinSortList.cpp b/C_plus/147*_InsertuinSortList.cpp deleted file mode 100644 index e42b9de..0000000 --- a/C_plus/147*_InsertuinSortList.cpp +++ /dev/null @@ -1,50 +0,0 @@ -/** - * Definition for singly-linked list. - * struct ListNode { - * int val; - * ListNode *next; - * ListNode() : val(0), next(nullptr) {} - * ListNode(int x) : val(x), next(nullptr) {} - * ListNode(int x, ListNode *next) : val(x), next(next) {} - * }; - */ -class Solution -{ -public: - ListNode *insertionSortList(ListNode *head) - { - - // option1 - // 因為串列特性, - // 1. 新增一個串列,每次搜尋一個節點, - // 2. 與串列從頭每個元素作比較,直到大於該元素,並插入 - // option 1 insert sort - if (!head || !head->next) - return head; - ListNode *ret = head, *cur = head->next; - ret->next = nullptr; - while (cur) - { - ListNode *k = cur; - cur = cur->next; - ListNode *j = ret, *pre = ret; - while (j && j->val < k->val) - { - pre = j; - j = j->next; - } - if (j == ret) - { - // insert first; - k->next = ret; - ret = k; - } - else - { - pre->next = k; - k->next = j; - } - } - return ret; - } -}; \ No newline at end of file diff --git a/C_plus/1472*_DesignBrowserHistory.cpp b/C_plus/1472*_DesignBrowserHistory.cpp deleted file mode 100644 index 1bc09a3..0000000 --- a/C_plus/1472*_DesignBrowserHistory.cpp +++ /dev/null @@ -1,43 +0,0 @@ -class BrowserHistory -{ -private: - string stack[5005]; - int p, t; // current pointer, stack's top - -public: - BrowserHistory(string homepage) - { - int p = 0, t = 0; - stack[0] = homepage; - } - - void visit(string url) - { - // stack[t = ++p] = url; - p++; - t = p; - stack[t] = url; - } - - string back(int steps) - { - // return stack[p = max(0, p-steps)]; - p = max(0, p - steps); - return stack[p]; - } - - string forward(int steps) - { - // return stack[p = min(t, p+steps)]; - p = min(t, p + steps); - return stack[p]; - } -}; - -/** - * Your BrowserHistory object will be instantiated and called as such: - * BrowserHistory* obj = new BrowserHistory(homepage); - * obj->visit(url); - * string param_2 = obj->back(steps); - * string param_3 = obj->forward(steps); - */ \ No newline at end of file diff --git a/C_plus/148*_SortedList.cpp b/C_plus/148*_SortedList.cpp deleted file mode 100644 index 278fa59..0000000 --- a/C_plus/148*_SortedList.cpp +++ /dev/null @@ -1,107 +0,0 @@ -/** - * Definition for singly-linked list. - * struct ListNode { - * int val; - * ListNode *next; - * ListNode() : val(0), next(nullptr) {} - * ListNode(int x) : val(x), next(nullptr) {} - * ListNode(int x, ListNode *next) : val(x), next(next) {} - * }; - */ -class Solution -{ -public: - ListNode *sortList(ListNode *head) - { - // option 0 beacause of return , so can use STL story each node and generate linked list - // if(!head || !head->next) return head; - // vector v; - // ListNode *p = head; - // while(p){ - // v.emplace_back(p->val); - // p=p->next; - // } - // sort(v.begin(), v.end()); - // ListNode *ret = new ListNode(v[0]); - // p =ret; - // for(int i=1;inext){ - // p->next = new ListNode(v[i]); - // } - // return ret; - - // option 1 insert sort - // O(n^2) => time out - if (!head || !head->next) - return head; - ListNode *ret = head, *p = ret; - ListNode *cur = head->next; - ret->next = nullptr; - while (cur) - { - ListNode *k = cur; - cur = cur->next; - ListNode *j = ret, *pre = ret; - while (j && j->val < k->val) - { - pre = j; - j = j->next; - } - if (j == ret) - { - // insert first node - k->next = j; - ret = k; - } - else - { - pre->next = k; - k->next = j; - } - } - - return ret; - - // option 2 O(nlogn) , so quick sort or quick sort - // merge sort - // 1. split each node using slow fast point - // 2. merge strategy - if (!head || !head->next) - return head; - ListNode *slow = head, *fast = head, *pre = head; - while (fast && fast->next) - { - pre = slow; - slow = slow->next; - fast = fast->next->next; - } - pre->next = nullptr; - - return merge(sortList(head), sortList(slow)); - } - ListNode *merge(ListNode *l1, ListNode *l2) - { - ListNode *cur = new ListNode(0), *ret = cur; - - while (l1 && l2) - { - if (l1->val < l2->val) - { - cur->next = l1; - cur = cur->next; - l1 = l1->next; - } - else - { - cur->next = l2; - cur = cur->next; - l2 = l2->next; - } - } - if (l1) - cur->next = l1; - if (l2) - cur->next = l2; - - return ret->next; - } -}; \ No newline at end of file diff --git a/C_plus/14_LongestCommonPrefix.cpp b/C_plus/14_LongestCommonPrefix.cpp deleted file mode 100644 index c254e67..0000000 --- a/C_plus/14_LongestCommonPrefix.cpp +++ /dev/null @@ -1,27 +0,0 @@ -class Solution -{ -public: - string longestCommonPrefix(vector &strs) - { - // O(n^2) - string ret = ""; - int len = strs.size(); - for (int i = 0; i < strs[0].size(); ++i) - { - char cand = strs[0][i]; - int count = 1; - for (int j = 1; j < len; ++j) - { - if (strs[j][i] == cand) - count++; - else - break; - } - if (count == len) - ret += cand; - else - break; - } - return ret; - } -}; \ No newline at end of file diff --git a/C_plus/15*_3Sum.cpp b/C_plus/15*_3Sum.cpp deleted file mode 100644 index 03af561..0000000 --- a/C_plus/15*_3Sum.cpp +++ /dev/null @@ -1,36 +0,0 @@ -class Solution -{ -public: - vector > threeSum(vector &nums) - { - // option 1 two pointer O(n^2) time and O(1) space - sort(nums.begin(), nums.end()); - vector > ret; - int n = nums.size(); - for (int i = 0; i < n - 2; ++i) - { - if (i > 0 && nums[i - 1] == nums[i]) - continue; - int l = i + 1, r = n - 1; - int target = -nums[i]; - while (l < r) - { - if (nums[l] + nums[r] == target) - { - ret.push_back({nums[i], nums[l], nums[r]}); - while (l < r && nums[l] == nums[l + 1]) - l++; - while (l < r && nums[r] == nums[r - 1]) - r--; - l++; - r--; - } - else if (nums[l] + nums[r] < target) - l++; - else - r--; - } - } - return ret; - } -}; \ No newline at end of file diff --git a/C_plus/150_EvaluateReversePolishNotation.cpp b/C_plus/150_EvaluateReversePolishNotation.cpp deleted file mode 100644 index 340e7ac..0000000 --- a/C_plus/150_EvaluateReversePolishNotation.cpp +++ /dev/null @@ -1,34 +0,0 @@ -class Solution -{ -public: - int evalRPN(vector &tokens) - { - // O(n) - stack sta; - for (string str : tokens) - { - if (!(str == "+" || str == "-" || str == "*" || str == "/")) - sta.push(stoi(str)); - - else - { - int b = sta.top(); - sta.pop(); - int a = sta.top(); - sta.pop(); - int tmp; - if (str == "+") - tmp = a + b; - else if (str == "-") - tmp = a - b; - else if (str == "*") - tmp = a * b; - else if (str == "/") - tmp = a / b; - sta.push(tmp); - } - } - - return sta.top(); - } -}; \ No newline at end of file diff --git a/C_plus/151_ReverseWordsinaString.cpp b/C_plus/151_ReverseWordsinaString.cpp deleted file mode 100644 index d05e52c..0000000 --- a/C_plus/151_ReverseWordsinaString.cpp +++ /dev/null @@ -1,57 +0,0 @@ -class Solution -{ -public: - string reverseWords(string s) - { - int l = 0, n = s.size(); - while (l < n && s[l] == ' ') - l++; - int r = l; - int last = n - 1; - while (s[last] == ' ') - last--; - vector ret; - for (int i = r; i <= last; ++i) - { - if (s[i] == ' ') - { - ret.push_back(s.substr(l, i - l)); - while (s[i] == ' ') - i++; - l = i; - } - } - ret.push_back(s.substr(l, last - l + 1)); - string ans; - - reverse(ret.begin(), ret.end()); - for (string str : ret) - ans += str + ' '; - return ans.substr(0, ans.size() - 1); - - - - //option 2 - int n = s.size(); - reverse(s.begin(), s.end()); - string ret; - int l=0, r=n-1; - while(l &nums) - { - // 維護兩組dp 一個放累積最大,一個放累積最小。 - // 注意,最小值可能乘以一個負數而變最大。 - // option 1 dp - // 2 3 -2 4 - //max 2 6 -2 4 - //min 2 3 -12 -48 - - // int m = nums.size(); - // vector _max(m,0), _min(m,0); - // _max[0] = nums[0]; - // _min[0] = nums[0]; - // int ret = nums[0]; - // for(int i=1;i &nums) - { - // priority queue O(nlogn) - - // priority_queue, greater> pq; - // for(int n:nums) pq.push(n); - // return pq.top(); - - // O(n) - // int ret = INT_MAX; - // for(int n:nums) ret = min(ret, n); - // return ret; - - // binary search - int n = nums.size(), l = 0, r = n - 1; - while (l < r) - { - int mid = l + (r - l) / 2; - if (nums[mid] > nums[r]) - l = mid + 1; - else - r = mid; - } - return nums[r]; - - // option 2 - int ret = nums[0]; - int n = nums.size(), l = 0, r = n-1; - while(l<=r){ - - int mid = l + (r-l)/2; - ret = min(nums[mid], ret); - if(nums[r] >=nums[mid]) r = mid -1; - else l = mid+1; - } - - return ret; - } -}; \ No newline at end of file diff --git a/C_plus/154*_FindMinimuminRotatedSortedArrayII.cpp b/C_plus/154*_FindMinimuminRotatedSortedArrayII.cpp deleted file mode 100644 index f3d1954..0000000 --- a/C_plus/154*_FindMinimuminRotatedSortedArrayII.cpp +++ /dev/null @@ -1,37 +0,0 @@ -class Solution -{ -public: - int findMin(vector &nums) - { - // option 1 O(n) - // use priority queue to cancel duplicate - // priority_queue, greater> pq; - // for(int n:nums) pq.push(n); - // return pq.top(); - - // O(nlogn) - int l = 0, r = nums.size() - 1; - while (l < r) - { - int mid = l + (r - l) / 2; - if (nums[mid] > nums[r]) - l = mid + 1; - // 讓子彈飛久一點 - else - r--; - } - return nums[l]; - - // option 2 - int n = nums.size(), l = 0, r = n-1; - int ret = nums.front(); - while(l<=r){ - int mid = l + (r-l)/2; - ret = min(ret, nums[mid]); - if(nums[mid] < nums[r]) r = mid-1; - else if(nums[mid] > nums[r]) l = mid+1; - else r--; // 讓子彈飛久一點 - } - return ret; - } -}; \ No newline at end of file diff --git a/C_plus/1541*_MinimumInsertionstoBalanceaParenthesesString.cpp b/C_plus/1541*_MinimumInsertionstoBalanceaParenthesesString.cpp deleted file mode 100644 index 889701e..0000000 --- a/C_plus/1541*_MinimumInsertionstoBalanceaParenthesesString.cpp +++ /dev/null @@ -1,35 +0,0 @@ -class Solution { -public: - int minInsertions(string s) { - - // need 變數 紀錄右括號 的需求量 - int ret = 0, need = 0; - - for(int i=0;i minsta; - stack sta; - - MinStack() - { - } - - void push(int val) - { - sta.push(val); - if (minsta.empty() || val <= minsta.top()) - minsta.push(val); - } - - void pop() - { - int tmp; - - tmp = sta.top(); - sta.pop(); - - if (!minsta.empty() && tmp == minsta.top()) - minsta.pop(); - } - - int top() - { - return sta.top(); - } - - int getMin() - { - return minsta.top(); - } -}; - -/** - * Your MinStack object will be instantiated and called as such: - * MinStack* obj = new MinStack(); - * obj->push(val); - * obj->pop(); - * int param_3 = obj->top(); - * int param_4 = obj->getMin(); - */ \ No newline at end of file diff --git a/C_plus/1567*_MaximumLengthofSubarrayWithPositiveProduct.cpp b/C_plus/1567*_MaximumLengthofSubarrayWithPositiveProduct.cpp deleted file mode 100644 index 8df6764..0000000 --- a/C_plus/1567*_MaximumLengthofSubarrayWithPositiveProduct.cpp +++ /dev/null @@ -1,70 +0,0 @@ -class Solution -{ -public: - int getMaxLen(vector &nums) - { - // 1 -2 -3 4 - //mx 1 0 3 4 - //mn 0 2 1 2 - - // 0 1 -2 -3 -4 - //mx 0 1 0 3 4 - //mn 0 0 2 1 2 - // option 1 O(n) time ans O(n) space - // dp - // int n = nums.size(); - // vector mx(n,0), mn(n,0); - // if(nums[0]>0){ - // mx[0] = 1; - // } - // else if(nums[0]<0){ - // mn[0] = 1; - // } - // int ret = mx[0]; - // // 遇到正數 mx[i] = mx[i-1]+1 , mn[i] = mn[i-1]+1; - // // 遇到負數 mx[i] = mn[i-1]+1 , mn[i] = mx[i-1]+1; - // for(int i =1;i0){ - // mx[i] = mx[i-1]+1; - // if(mn[i-1]>0) mn[i] = mn[i-1]+1;// max(mn[i-1]+1, mn[i]); - // } - // else{ - // mn[i] = mx[i-1] +1 ; - // if(mn[i-1]>0) mx[i] = mn[i-1]+1 ; //max(mn[i-1]+1, mx[i]); - // } - // ret = max(ret, mx[i]); - // } - // return ret; - - // option 2 O(n) time ans O(1) space - // reduce dp - int p = 0, n = 0, ret = 0; - for (int x : nums) - { - if (x == 0) - { - p = n = 0; - } - else if (x > 0) - { - p = p + 1; - if (n) - n++; - } - else - { - int tmp = p; - if (n) - p = n + 1; - else - p = 0; - n = tmp + 1; - } - ret = max(ret, p); - } - return ret; - } -}; \ No newline at end of file diff --git a/C_plus/1588*_SumofAllOddLengthSubarrays.cpp b/C_plus/1588*_SumofAllOddLengthSubarrays.cpp deleted file mode 100644 index 0eafc31..0000000 --- a/C_plus/1588*_SumofAllOddLengthSubarrays.cpp +++ /dev/null @@ -1,23 +0,0 @@ -class Solution -{ -public: - int sumOddLengthSubarrays(vector &arr) - { - // option 1 O(n^3) - // can refer https://web.stanford.edu/class/cs9/sample_probs/SubarraySums.pdf - - - int ret = 0, n = arr.size(); - for (int i = 1; i <= n; i += 2) - { // i =1,3,5,7,9 - int k = 0; - while (k + i - 1 < n) - { - int sum = accumulate(arr.begin() + k, arr.begin() + k + i, 0); - k++; - ret += sum; - } - } - return ret; - } -}; \ No newline at end of file diff --git a/C_plus/1594*_MAximumNonNegativeProductinaMatrix.cpp b/C_plus/1594*_MAximumNonNegativeProductinaMatrix.cpp deleted file mode 100644 index 1b79d63..0000000 --- a/C_plus/1594*_MAximumNonNegativeProductinaMatrix.cpp +++ /dev/null @@ -1,60 +0,0 @@ -class Solution -{ -public: - int maxProductPath(vector > &grid) - { - - // option 1 maintain two dp to dividually store max and min value until now; - int n = grid.size(), m = grid[0].size(); - vector > maxCache(n, vector(m, 0)); - vector > minCache(n, vector(m, 0)); - - long long mod = 1e9 + 7; - - for (int i = 0; i < n; ++i) - { - for (int j = 0; j < m; ++j) - { - - long maxVal = INT_MIN, minVal = INT_MAX; - if (i == 0 && j == 0) - { - maxVal = grid[i][j]; - minVal = grid[i][j]; - } - - else if (i == 0) - { - long tempMax = max(grid[i][j] * minCache[i][j - 1], grid[i][j] * maxCache[i][j - 1]); - maxVal = max(maxVal, tempMax); - - long tempMin = min(grid[i][j] * minCache[i][j - 1], grid[i][j] * maxCache[i][j - 1]); - minVal = min(minVal, tempMin); - } - else if (j == 0) - { - long tempMax = max(grid[i][j] * minCache[i - 1][j], grid[i][j] * maxCache[i - 1][j]); - maxVal = max(maxVal, tempMax); - - long tempMin = min(grid[i][j] * minCache[i - 1][j], grid[i][j] * maxCache[i - 1][j]); - minVal = min(minVal, tempMin); - } - else - { - long tempMax = max(grid[i][j] * minCache[i - 1][j], grid[i][j] * minCache[i][j - 1]); - maxVal = max(maxVal, tempMax); - tempMax = max(grid[i][j] * maxCache[i - 1][j], grid[i][j] * maxCache[i][j - 1]); - maxVal = max(maxVal, tempMax); - - long tempMin = min(grid[i][j] * minCache[i - 1][j], grid[i][j] * minCache[i][j - 1]); - minVal = min(minVal, tempMin); - tempMin = min(grid[i][j] * maxCache[i - 1][j], grid[i][j] * maxCache[i][j - 1]); - minVal = min(minVal, tempMin); - } - maxCache[i][j] = maxVal; - minCache[i][j] = minVal; - } - } - return maxCache[n - 1][m - 1] < 0 ? -1 : maxCache[n - 1][m - 1] % mod; - } -}; \ No newline at end of file diff --git a/C_plus/16*_3SumClosest.cpp b/C_plus/16*_3SumClosest.cpp deleted file mode 100644 index b06aac2..0000000 --- a/C_plus/16*_3SumClosest.cpp +++ /dev/null @@ -1,33 +0,0 @@ -class Solution -{ -public: - int threeSumClosest(vector &nums, int target) - { - // O(n^2) time and O(1) space - sort(nums.begin(), nums.end()); - int ret = nums[0] + nums[1] + nums[2]; - int cand = 0; - for (int i = 0; i < nums.size() - 2; ++i) - { - int j = i + 1, k = nums.size() - 1; - while (j < k) - { - cand = nums[i] + nums[j] + nums[k]; - if (cand == target) - return cand; - - else if (cand < target) - { - j++; - } - else - { - k--; - } - if (abs(target - ret) > abs(target - cand)) - ret = cand; - } - } - return ret; - } -}; \ No newline at end of file diff --git a/C_plus/160_IntersectionOrTwoLinkedList.cpp b/C_plus/160_IntersectionOrTwoLinkedList.cpp deleted file mode 100644 index 07cc00c..0000000 --- a/C_plus/160_IntersectionOrTwoLinkedList.cpp +++ /dev/null @@ -1,64 +0,0 @@ -/** - * Definition for singly-linked list. - * struct ListNode { - * int val; - * ListNode *next; - * ListNode(int x) : val(x), next(NULL) {} - * }; - */ -class Solution -{ -public: - ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) - { - - // option 1 - // 1. 是否有相同終點以判斷是否有交集 - // 2. 如果有交集,讓長串列先走幾步 - int asize = 0, bsize = 0; - for (ListNode *p = headA; p; p = p->next) - asize++; - for (ListNode *p = headB; p; p = p->next) - bsize++; - ListNode *pa = headA, *pb = headB; - while (pa->next) - pa = pa->next; - while (pb->next) - pb = pb->next; - if (pa != pb) - return nullptr; - - /* Set pointers to the start of each linked list. */ - ListNode *longer = (asize >= bsize) ? headA : headB; - ListNode *shorter = (asize < bsize) ? headA : headB; - - // get k node in the linked list - int len = abs(asize - bsize); - while (len) - { - longer = longer->next; - len--; - } - - /* Move both pointers until you have a collision. */ - while (shorter != longer) - { - shorter = shorter->next; - longer = longer->next; - } - return shorter; - - // option 2 - - // ListNode *a = headA, *b = headB; - - // while(a!=b){ - - // if(a==nullptr) a = headB; - // else a=a->next; - // if(b==nullptr) b = headA; - // else b=b->next; - // } - // return a; - } -}; \ No newline at end of file diff --git a/C_plus/162*_FindPeakElement.cpp b/C_plus/162*_FindPeakElement.cpp deleted file mode 100644 index 948e46f..0000000 --- a/C_plus/162*_FindPeakElement.cpp +++ /dev/null @@ -1,79 +0,0 @@ -class Solution -{ -public: - int findPeakElement(vector &nums) - { - // option 1 brute O(n) - // int n=nums.size(); - // if (nums.size() == 1) return 0; - // for(int i=0;inums[i+1]) return i; - // else if(i==n-1 && nums[i]> nums[i-1]) return i; - // } - // else{ - // if( nums[i]>nums[i-1] && nums[i]>nums[i+1]) return i; - // } - // } - // return -1; - - // option 2 simplify option 1 , 因為nums[i] != nums[i + 1],直接在兩端加入最小值 - // if (nums.size() == 1) return 0; - // nums.insert(nums.begin(), INT_MIN); - // nums.push_back(INT_MIN); - // for (int i = 1; i < (int)nums.size() - 1; ++i) { - // if (nums[i] > nums[i - 1] && nums[i] > nums[i + 1]) return i - 1; - // } - // return -1; - - // option 3 一定存在至少一個山峰 - for (int i = 1; i < nums.size(); ++i) - { - if (nums[i] < nums[i - 1]) - return i - 1; - } - return nums.size() - 1; - - // option 4 因為題目限制O(nlogn) 讓我想到 binary search,直接在兩端加入最小值,但返回值需要注意mid-1 - // int n=nums.size(); - // if(n<2) return 0; - // nums.insert(nums.begin(), INT_MIN); - // nums.push_back(INT_MIN); - // return BinarySearch(nums, nums.size() ); - - // option 5 簡化 option 4 - int l = 0, r = nums.size() - 1; - while (l < r) - { - int mid = l + (r - l) / 2; - if (nums[mid] < nums[mid + 1]) - l = mid + 1; - else - r = mid; - } - return r; - } - int BinarySearch(vector &nums, int n) - { - - int l = 0, r = n - 1; - while (l <= r) - { - int mid = l + (r - l) / 2; - cout << mid << endl; - if (mid - 1 >= 0 && mid + 1 <= n - 1) - { - if (nums[mid] > nums[mid - 1] && nums[mid] > nums[mid + 1]) - return mid - 1; - else if (nums[mid - 1] > nums[mid] && nums[mid] > nums[mid + 1]) - r = mid; - else - l = mid + 1; - } - else - break; - } - - return r; - } -}; \ No newline at end of file diff --git a/C_plus/1629_Slowest Key.cpp b/C_plus/1629_Slowest Key.cpp deleted file mode 100644 index 7b27395..0000000 --- a/C_plus/1629_Slowest Key.cpp +++ /dev/null @@ -1,26 +0,0 @@ -class Solution -{ -public: - char slowestKey(vector &releaseTimes, string keysPressed) - { - char ret; - int val = 0; - int n = releaseTimes.size(); - ret = keysPressed[0], val = releaseTimes[0]; - for (int i = 1; i < n; ++i) - { - int time = releaseTimes[i] - releaseTimes[i - 1]; - if (time > val) - { - val = time; - ret = keysPressed[i]; - } - else if (time == val) - { - if (ret - 'a' < keysPressed[i] - 'a') - ret = keysPressed[i]; - } - } - return ret; - } -}; \ No newline at end of file diff --git a/C_plus/1636_SortArraybyIncreasingFrequency.cpp b/C_plus/1636_SortArraybyIncreasingFrequency.cpp deleted file mode 100644 index b3a99c9..0000000 --- a/C_plus/1636_SortArraybyIncreasingFrequency.cpp +++ /dev/null @@ -1,30 +0,0 @@ -class Solution -{ -public: - vector frequencySort(vector &nums) - { - - unordered_map m; - vector > vec; - for (int n : nums) - m[n]++; - vector ret; - for (auto it = m.begin(); it != m.end(); ++it) - { - vec.push_back({it->first, it->second}); - } - sort(vec.begin(), vec.end(), [](vector &a, vector &b) - { - if (a[1] == b[1]) - return a[0] > b[0]; - else - return a[1] < b[1]; - }); - for (int i = 0; i < vec.size(); ++i) - { - for (int _ = 0; _ < vec[i][1]; ++_) - ret.push_back(vec[i][0]); - } - return ret; - } -}; \ No newline at end of file diff --git a/C_plus/164*_MaximumGap.cpp b/C_plus/164*_MaximumGap.cpp deleted file mode 100644 index 54dbf59..0000000 --- a/C_plus/164*_MaximumGap.cpp +++ /dev/null @@ -1,50 +0,0 @@ -class Solution -{ -public: - int maximumGap(vector &nums) - { - // option 1 O(nlogn) - // if(nums.size()==1) return 0; - // int ret = 0, n = nums.size(); - // sort(nums.begin(), nums.end()); // O(nlogn) - // for(int i=1;i bucketsMin(m, INT_MAX); - vector bucketsMax(m, INT_MIN); - for (int num : nums) - { - int k = (num - global_min) / gap; - if (num < bucketsMin[k]) - bucketsMin[k] = num; - if (num > bucketsMax[k]) - bucketsMax[k] = num; - } - - int i = 0, j; - gap = bucketsMax[0] - bucketsMin[0]; - while (i < m) - { - j = i + 1; - while (j < m && bucketsMin[j] == INT_MAX && bucketsMax[j] == INT_MIN) - j++; - if (j == m) - break; - gap = max(gap, bucketsMin[j] - bucketsMax[i]); - i = j; - } - return gap; - } -}; \ No newline at end of file diff --git a/C_plus/1646_GetMaximuminGeneratedArray.cpp b/C_plus/1646_GetMaximuminGeneratedArray.cpp deleted file mode 100644 index b780abf..0000000 --- a/C_plus/1646_GetMaximuminGeneratedArray.cpp +++ /dev/null @@ -1,24 +0,0 @@ -class Solution -{ -public: - int getMaximumGenerated(int n) - { - // option 1 dp - vector dp(n + 1, 0); - int ret = 0; - int k = 0; - if (n < 2) - return n; - dp[0] = 0; - dp[1] = 1; - for (int i = 2; i <= n; i++) - { - if (i % 2 == 0) - dp[i] = dp[i / 2]; - else - dp[i] = dp[i / 2] + dp[i / 2 + 1]; - ret = max(dp[i], ret); - } - return ret; - } -}; \ No newline at end of file diff --git a/C_plus/165_CompareVersionNumbers.cpp b/C_plus/165_CompareVersionNumbers.cpp deleted file mode 100644 index 180b20a..0000000 --- a/C_plus/165_CompareVersionNumbers.cpp +++ /dev/null @@ -1,69 +0,0 @@ -class Solution -{ -public: - vector make(string version) - { - vector ver; - int l = 0; - int ret = 0; - while (l < version.size()) - { - if (version[l] == '.') - { - ver.push_back(ret); - - ret = 0; - } - else - { - ret = 10 * ret + (version[l] - '0'); - } - l++; - } - if (ret != 0) - ver.push_back(ret); - - return ver; - } - int compareVersion(string version1, string version2) - { - // - - vector ver1 = make(version1); - vector ver2 = make(version2); - int l = 0, r = 0; - while (l < ver1.size() && r < ver2.size()) - { - - if (ver1[l] == ver2[r]) - { - l++; - r++; - } - else if (ver1[l] > ver2[r]) - { - return 1; - } - else - { - return -1; - } - } - - while (l < ver1.size()) - { - if (ver1[l] == 0) - l++; - else - return 1; - } - while (r < ver2.size()) - { - if (ver2[r] == 0) - r++; - else - return -1; - } - return 0; - } -}; \ No newline at end of file diff --git a/C_plus/1669_MergeInBetweenLinkedLists.cpp b/C_plus/1669_MergeInBetweenLinkedLists.cpp deleted file mode 100644 index 05f0006..0000000 --- a/C_plus/1669_MergeInBetweenLinkedLists.cpp +++ /dev/null @@ -1,56 +0,0 @@ -/** - * Definition for singly-linked list. - * struct ListNode { - * int val; - * ListNode *next; - * ListNode() : val(0), next(nullptr) {} - * ListNode(int x) : val(x), next(nullptr) {} - * ListNode(int x, ListNode *next) : val(x), next(next) {} - * }; - */ -class Solution -{ -public: - ListNode *mergeInBetween(ListNode *list1, int a, int b, ListNode *list2) - { - // option 1 vreate new linked list - // ListNode *ret = new ListNode(0), *p=ret; - // ListNode *cur = list1; - // while(a){ - // p->next = new ListNode(cur->val); - // p=p->next; - // cur=cur->next; - // a--; - // } - // cur =list2; - // while(cur){ - // p->next = new ListNode(cur->val); - // p=p->next; - // cur=cur->next; - // } - - // cur=list1; - // while(b){ - // cur=cur->next; - // b--; - // } - // cur=cur->next; - // while(cur){ - // p->next = new ListNode(cur->val); - // p=p->next; - // cur=cur->next; - // } - // return ret->next; - // option 2 in-place modify with two pointer - ListNode *la = list1, *lb = la; - for (int i = 0; i < a - 1; ++i) - la = la->next; - for (int i = 0; i <= b; ++i) - lb = lb->next; - la->next = list2; - while (list2->next) - list2 = list2->next; - list2->next = lb; - return list1; - } -}; \ No newline at end of file diff --git a/C_plus/1670*_DesignFrontMiddleBackQueue.cpp b/C_plus/1670*_DesignFrontMiddleBackQueue.cpp deleted file mode 100644 index 5e82eef..0000000 --- a/C_plus/1670*_DesignFrontMiddleBackQueue.cpp +++ /dev/null @@ -1,148 +0,0 @@ -// option 1 O(n) -// class FrontMiddleBackQueue { -// private: -// vector nums; -// public: -// FrontMiddleBackQueue() { -// } - -// void pushFront(int val) { -// nums.emplace(nums.begin(), val); -// } - -// void pushMiddle(int val) { -// int mid = nums.size()/2; -// nums.emplace(nums.begin()+mid, val); -// cout<pushFront(val); - * obj->pushMiddle(val); - * obj->pushBack(val); - * int param_4 = obj->popFront(); - * int param_5 = obj->popMiddle(); - * int param_6 = obj->popBack(); - */ - -// option 2 maintain two deque ,一個是前半段,另一個是後半段 -// 提供兩個函數使得能在常數時間獲取中間數字 -class FrontMiddleBackQueue -{ -private: - deque first, second; - void a2b() - { - if (first.size() <= second.size()) - return; - second.push_front(first.back()); - first.pop_back(); - } - void b2a() - { - if (second.size() <= first.size() + 1) - return; - first.push_back(second.front()); - second.pop_front(); - } - -public: - FrontMiddleBackQueue() - { - } - - void pushFront(int val) - { - first.push_front(val); - a2b(); - } - - void pushMiddle(int val) - { - first.push_back(val); - a2b(); - } - - void pushBack(int val) - { - second.push_back(val); - b2a(); - } - - int popFront() - { - if (first.empty() && second.empty()) - return -1; - int ans; - if (first.empty()) - { - ans = second.front(); - second.pop_front(); - } - else - { - ans = first.front(); - first.pop_front(); - b2a(); - } - return ans; - } - - int popMiddle() - { - if (first.empty() && second.empty()) - return -1; - int ans; - if (first.size() == second.size()) - { - ans = first.back(); - first.pop_back(); - } - else - { - ans = second.front(); - second.pop_front(); - } - return ans; - } - - int popBack() - { - if (first.empty() && second.empty()) - return -1; - int ans = second.back(); - second.pop_back(); - a2b(); - return ans; - } -}; diff --git a/C_plus/167_TwoSum.cpp b/C_plus/167_TwoSum.cpp deleted file mode 100644 index ff39e58..0000000 --- a/C_plus/167_TwoSum.cpp +++ /dev/null @@ -1,49 +0,0 @@ -class Solution -{ -public: - vector twoSum(vector &numbers, int target) - { - // option 0 - // binary search O(nlogn) time and O(1) space - // 選定 索引為 i 的數字 ,在用binary search 找 另一個數字使總和為target - int n = numbers.size(); - - for(int i=0;inumbers[l] + numbers[r]) l++; - // else if(target m; - for (int i = 0; i < numbers.size(); ++i) - { - - if (m.find(target - numbers[i]) != m.end()) - return {m[target - numbers[i]] + 1, i + 1}; - m[numbers[i]] = i; - } - return {}; - } -}; \ No newline at end of file diff --git a/C_plus/168_ExcelSheetColumnTitle.cpp b/C_plus/168_ExcelSheetColumnTitle.cpp deleted file mode 100644 index b744d5c..0000000 --- a/C_plus/168_ExcelSheetColumnTitle.cpp +++ /dev/null @@ -1,17 +0,0 @@ -class Solution -{ -public: - string convertToTitle(int columnNumber) - { - int n = columnNumber; - string ret = ""; - while (n) - { - n--; - char c = 'A' + (n % 26); - ret = c + ret; - n /= 26; - } - return ret; - } -}; \ No newline at end of file diff --git a/C_plus/169_MajorityElement.cpp b/C_plus/169_MajorityElement.cpp deleted file mode 100644 index b97ea11..0000000 --- a/C_plus/169_MajorityElement.cpp +++ /dev/null @@ -1,27 +0,0 @@ -class Solution -{ -public: - int majorityElement(vector &nums) - { - // option 1 O(nlogn) - // sort(nums.begin(), nums.end()); - // return nums[nums.size()/2]; - - // option 2 O(n) and O(1) space - int ret; - int count = 0; - for (int i = 0; i < nums.size(); ++i) - { - if (count == 0) - { - ret = nums[i]; - count++; - } - else if (nums[i] == ret) - count++; - else - count--; - } - return ret; - } -}; \ No newline at end of file diff --git a/C_plus/171_ExcelSheetColumnNumber.cpp b/C_plus/171_ExcelSheetColumnNumber.cpp deleted file mode 100644 index 1fa514f..0000000 --- a/C_plus/171_ExcelSheetColumnNumber.cpp +++ /dev/null @@ -1,14 +0,0 @@ -class Solution -{ -public: - int titleToNumber(string columnTitle) - { - int ret = 0; - for (char c : columnTitle) - { - ret *= 26; - ret += (c - 'A' + 1); - } - return ret; - } -}; \ No newline at end of file diff --git a/C_plus/172*_FactorialTralingZeros.cpp b/C_plus/172*_FactorialTralingZeros.cpp deleted file mode 100644 index 6b24645..0000000 --- a/C_plus/172*_FactorialTralingZeros.cpp +++ /dev/null @@ -1,18 +0,0 @@ -class Solution -{ -public: - int trailingZeroes(int n) - { - // option 1 - // 看有幾個5,就有幾個0 avoid overflow; - int ret = 0; - for(int d = n;d>4 ;d/=5){ - ret += d/5; - } - return ret; - - // option 2 - // if(n<5) return 0;; - // return n/5 + trailingZeroes(n/5); - } -}; \ No newline at end of file diff --git a/C_plus/1721_SwappingNodesinaLinkedList.cpp b/C_plus/1721_SwappingNodesinaLinkedList.cpp deleted file mode 100644 index 194dfef..0000000 --- a/C_plus/1721_SwappingNodesinaLinkedList.cpp +++ /dev/null @@ -1,42 +0,0 @@ -/** - * Definition for singly-linked list. - * struct ListNode { - * int val; - * ListNode *next; - * ListNode() : val(0), next(nullptr) {} - * ListNode(int x) : val(x), next(nullptr) {} - * ListNode(int x, ListNode *next) : val(x), next(next) {} - * }; - */ -class Solution -{ -public: - ListNode *swapNodes(ListNode *head, int k) - { - // option 1 overwrite each other value - int len = 0; - for (ListNode *p = head; p; p = p->next) - len++; - // swap two node by index k , and len-k+1 - int n1 = k, n2 = len - k + 1; - ListNode *node1 = head, *node2 = head; - n1--; - while (n1) - { - node1 = node1->next; - n1--; - } - n2--; - while (n2) - { - node2 = node2->next; - n2--; - } - // swap - swap(node1->val, node2->val); - // int tmp = node1->val ; - // node1->val = node2->val; - // node2->val = tmp; - return head; - } -}; \ No newline at end of file diff --git a/C_plus/173*_BinarySearchTreeIterator.cpp b/C_plus/173*_BinarySearchTreeIterator.cpp deleted file mode 100644 index 1b66c2c..0000000 --- a/C_plus/173*_BinarySearchTreeIterator.cpp +++ /dev/null @@ -1,57 +0,0 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class BSTIterator { -private: - stacksta; -public: - BSTIterator(TreeNode* root) { - // inorder traverse - // O(h) space - TreeNode *p = root; - while(p){ - sta.push(p); - p=p->left; - } - - } - - int next() { - // O(1) time - TreeNode * p = sta.top(); - sta.pop(); - int ans = p->val; - if(p->right){ - p = p->right; - while(p){ - // 因為是BST 下一個節點並存在右子樹最小的節點,也就是右子樹的最左邊的葉子 - sta.push(p); - p=p->left; - } - } - - return ans; - - } - - bool hasNext() { - // O(1) time - return !sta.empty(); - - } -}; - -/** - * Your BSTIterator object will be instantiated and called as such: - * BSTIterator* obj = new BSTIterator(root); - * int param_1 = obj->next(); - * bool param_2 = obj->hasNext(); - */ \ No newline at end of file diff --git a/C_plus/1732_FindtheHighestAltitude.cpp b/C_plus/1732_FindtheHighestAltitude.cpp deleted file mode 100644 index 94b7492..0000000 --- a/C_plus/1732_FindtheHighestAltitude.cpp +++ /dev/null @@ -1,14 +0,0 @@ -class Solution -{ -public: - int largestAltitude(vector &gain) - { - int highest = 0, cur = 0; - for (int n : gain) - { - cur += n; - highest = max(cur, highest); - } - return highest; - } -}; \ No newline at end of file diff --git a/C_plus/174*_DungeonGame.cpp b/C_plus/174*_DungeonGame.cpp deleted file mode 100644 index 95013a5..0000000 --- a/C_plus/174*_DungeonGame.cpp +++ /dev/null @@ -1,68 +0,0 @@ -class Solution -{ -public: - vector > memo; - int dp(vector > &dungeon, int i, int j) - { - int m = dungeon.size(), n = dungeon[0].size(); - - // base case - if (i == m - 1 && j == n - 1) - { - // 保證騎士落地不死就行了 - return dungeon[i][j] > 0 ? 1 : -dungeon[i][j] + 1; - } - - if (i == m || j == n) - return INT_MAX; - - if (memo[i][j] != -1) - return memo[i][j]; - - int ret = min(dp(dungeon, i, j + 1), - dp(dungeon, i + 1, j)) - - dungeon[i][j]; - - memo[i][j] = ret <= 0 ? 1 : ret; - - return memo[i][j]; - } - int calculateMinimumHP(vector > &dungeon) - { - // backtracking - int m = dungeon.size(), n = dungeon[0].size(); - memo = vector >(m, vector(n, -1)); - - return dp(dungeon, 0, 0); - - // option 1 dp - // 7 5 2 - // 6 11 5 - // 1 1 6 - int n = dungeon.size(), m = dungeon[0].size(); - vector > dp(n, vector(m, 0)); - // base case - dp[n - 1][m - 1] = max(1, 1 - dungeon[n - 1][m - 1]); - for (int j = m - 2; j > -1; j--) - { - dp[n - 1][j] = max(1, dp[n - 1][j + 1] - dungeon[n - 1][j]); - } - - for (int i = n - 2; i > -1; i--) - { - dp[i][m - 1] = max(1, dp[i + 1][m - 1] - dungeon[i][m - 1]); - } - - // - for (int i = n - 2; i > -1; i--) - { - for (int j = m - 2; j > -1; j--) - { - dp[i][j] = min(max(1, dp[i + 1][j] - dungeon[i][j]), - max(1, dp[i][j + 1] - dungeon[i][j])); - } - } - - return dp[0][0]; - } -}; \ No newline at end of file diff --git a/C_plus/175*_CombineTwoTables.sql b/C_plus/175*_CombineTwoTables.sql deleted file mode 100644 index 23c81ae..0000000 --- a/C_plus/175*_CombineTwoTables.sql +++ /dev/null @@ -1,4 +0,0 @@ -# Write your MySQL query statement below - - -SELECT Person.FirstName, Person.LastName, Address.City, Address.State FROM Person LEFT JOIN Address ON Person.PersonId = Address.PersonId; diff --git a/C_plus/179*_LargestNumber.cpp b/C_plus/179*_LargestNumber.cpp deleted file mode 100644 index 0514c8e..0000000 --- a/C_plus/179*_LargestNumber.cpp +++ /dev/null @@ -1,41 +0,0 @@ -class Solution -{ -public: - string largestNumber(vector &nums) - { - - // 9xx , 8xx - // put bucket - - vector > bucket(10); - for (int n : nums) - { - string s = to_string(n); - int h = s[0] - '0'; - bucket[h].push_back(to_string(n)); - } - // sort - // 9 > 9991 - for (int i = 0; i <= 9; ++i) - { - sort(bucket[i].begin(), bucket[i].end(), [](string a, string b) - { return a + b > b + a; }); - } - string ret = ""; - for (int i = 9; i >= 0; i--) - { - if (bucket[i].empty()) - continue; - if (bucket[i].size() == 0) - continue; - for (string str : bucket[i]) - ret += str; - } - int l = 0; - while (l < ret.size() && ret[l] == '0') - l++; - - string str = ret.substr(l); - return str.empty() ? "0" : str; - } -}; \ No newline at end of file diff --git a/C_plus/17_LetterCombinationsOfAPhoneNumber.cpp b/C_plus/17_LetterCombinationsOfAPhoneNumber.cpp deleted file mode 100644 index 0d3a445..0000000 --- a/C_plus/17_LetterCombinationsOfAPhoneNumber.cpp +++ /dev/null @@ -1,61 +0,0 @@ -class Solution -{ -public: - void traverse(string digits, unordered_map &dict, vector &ret, string str, int l) - { - - if (digits.size() == str.size()) - { - ret.push_back(str); - return; - } - - for (char c : dict[digits[l] - '0']) - { - traverse(digits, dict, ret, str + c, l + 1); - } - } - vector letterCombinations(string digits) - { - // DFS - // vector ret; - // string str; - - // unordered_map dict = { - // {2, "abc"},{3, "def"}, {4,"ghi"}, {5,"jkl"}, {6,"mno"}, {7,"pqrs"}, {8,"tuv"}, {9,"wxyz"} - // }; - // if(digits.empty()) return ret; - // traverse(digits,dict, ret, str, 0); - // return ret; - - queue q; - unordered_map dict = { - {2, "abc"}, {3, "def"}, {4, "ghi"}, {5, "jkl"}, {6, "mno"}, {7, "pqrs"}, {8, "tuv"}, {9, "wxyz"}}; - for (char c : dict[digits[0] - '0']) - { - string d; - d.push_back(c); - q.push(d); - } - - vector ret; - for (int i = 1; i < digits.size(); ++i) - { - int size = q.size(); - for (int j = 0; j < size; ++j) - { - string temp = q.front(); - q.pop(); - for (char c : dict[digits[i] - '0']) - q.push(temp + c); - } - } - while (!q.empty()) - { - string s = q.front(); - q.pop(); - ret.push_back(s); - } - return ret; - } -}; \ No newline at end of file diff --git a/C_plus/187_RepeatedDNASequences.cpp b/C_plus/187_RepeatedDNASequences.cpp deleted file mode 100644 index 1d8cd11..0000000 --- a/C_plus/187_RepeatedDNASequences.cpp +++ /dev/null @@ -1,32 +0,0 @@ -class Solution -{ -public: - vector findRepeatedDnaSequences(string s) - { - - // slide window - string window; - unordered_map ret; - int l = 0, r = 0; - while (r < s.size()) - { - char c = s[r++]; - window += c; - if (r - l > 10) - { - char d = s[l++]; - window.erase(0, 1); - } - ret[window]++; - } - vector ans; - for (auto it = ret.begin(); it != ret.end(); ++it) - { - // cout<first<<" "<second<second > 1) - ans.push_back(it->first); - } - - return ans; - } -}; \ No newline at end of file diff --git a/C_plus/188*_BestTimetoBuyandSellStockIV.cpp b/C_plus/188*_BestTimetoBuyandSellStockIV.cpp deleted file mode 100644 index d367678..0000000 --- a/C_plus/188*_BestTimetoBuyandSellStockIV.cpp +++ /dev/null @@ -1,43 +0,0 @@ -class Solution -{ -public: - int maxProfit(vector &prices) - { - int n = prices.size(); - int dp_i_0 = 0, dp_i_1 = -prices[0]; - for (int i = 1; i < n; ++i) - { - int temp = dp_i_0; - dp_i_0 = max(dp_i_0, dp_i_1 + prices[i]); - dp_i_1 = max(dp_i_1, temp - prices[i]); - } - return dp_i_0; - } - - int maxProfit(int k, vector &prices) - { - if (prices.empty()) - return 0; - int n = prices.size(); - if (k > n / 2) - return maxProfit(prices); - // 因為一次買入和賣出,至少需要兩天,所以k應該不超過n/2。如果超過就相當於沒有約束,相當於k=+infinity - - vector > > dp(n, vector >(k + 1, vector(2, 0))); - for (int i = 0; i < n; ++i) - { - for (int kk = k; kk >= 1; kk--) - { - if (i == 0) - { - dp[i][kk][0] = 0; - dp[i][kk][1] = -prices[i]; - continue; - } - dp[i][kk][0] = max(dp[i - 1][kk][0], dp[i - 1][kk][1] + prices[i]); - dp[i][kk][1] = max(dp[i - 1][kk][1], dp[i - 1][kk - 1][0] - prices[i]); - } - } - return dp[n - 1][k][0]; - } -}; \ No newline at end of file diff --git a/C_plus/1886_DetermineWhetherMatrixCanBeObtainedByRotation.cpp b/C_plus/1886_DetermineWhetherMatrixCanBeObtainedByRotation.cpp deleted file mode 100644 index 014404b..0000000 --- a/C_plus/1886_DetermineWhetherMatrixCanBeObtainedByRotation.cpp +++ /dev/null @@ -1,23 +0,0 @@ -class Solution -{ -public: - bool findRotation(vector > &mat, vector > &target) - { - - for (int k = 0; k < 4; ++k) - { - reverse(mat.begin(), mat.end()); - int n = mat.size(); - for (int i = 0; i < n; ++i) - { - for (int j = i + 1; j < n; ++j) - { - swap(mat[i][j], mat[j][i]); - } - } - if (mat == target) - return true; - } - return false; - } -}; \ No newline at end of file diff --git a/C_plus/189*_RotateArray.cpp b/C_plus/189*_RotateArray.cpp deleted file mode 100644 index 65b4e87..0000000 --- a/C_plus/189*_RotateArray.cpp +++ /dev/null @@ -1,43 +0,0 @@ -class Solution -{ -public: - void rotate(vector &nums, int k) - { - - // option 1 tricky 作弊方法 space O(n) - // int n = nums.size(); - // k = k%n; - // int p = n-k; - // vector vec(n,0); - - // for(int i=0;i > &grid, int i, int j) - { - int n = grid.size(), m = grid[0].size(); - if (i < 0 || j < 0 || i > n - 1 || j > m - 1 || grid[i][j] == 0) - return; - - grid[i][j] = 0; - dfs(grid, i - 1, j); - dfs(grid, i, j - 1); - dfs(grid, i + 1, j); - dfs(grid, i, j + 1); - } - int countSubIslands(vector > &grid1, vector > &grid2) - { - - // 子島 ,假設 grid2 中島嶼的每一個cell都被grid1 的同一個島嶼完全包含,則視為子島 - // grid2 是陸地,但grid1 是海,那就淹掉, - int cnt = 0; - int n = grid1.size(), m = grid1[0].size(); - for (int i = 0; i < n; ++i) - { - for (int j = 0; j < m; ++j) - { - if (grid1[i][j] == 0 && grid2[i][j] == 1) - dfs(grid2, i, j); - } - } - - for (int i = 0; i < n; ++i) - { - for (int j = 0; j < m; ++j) - { - if (grid2[i][j] == 0) - continue; - cnt++; - dfs(grid2, i, j); - } - } - return cnt; - } -}; \ No newline at end of file diff --git a/C_plus/190_ReverseBits.cpp b/C_plus/190_ReverseBits.cpp deleted file mode 100644 index c3d8e2c..0000000 --- a/C_plus/190_ReverseBits.cpp +++ /dev/null @@ -1,16 +0,0 @@ -class Solution -{ -public: - uint32_t reverseBits(uint32_t n) - { - uint32_t ret = 0; - - for (int i = 0; i < 32; ++i) - { - ret <<= 1; - ret += (n & 1); - n >>= 1; - } - return ret; - } -}; \ No newline at end of file diff --git a/C_plus/1913_MaximumProductDifferenceBetweenTwoPairs.cpp b/C_plus/1913_MaximumProductDifferenceBetweenTwoPairs.cpp deleted file mode 100644 index b8b6107..0000000 --- a/C_plus/1913_MaximumProductDifferenceBetweenTwoPairs.cpp +++ /dev/null @@ -1,40 +0,0 @@ -class Solution -{ -public: - int maxProductDifference(vector &nums) - { - // option 1 O(nlogn) sorting - - // sort(nums.begin(), nums.end()); - // int n = nums.size()-1; - // return nums[n]*nums[n-1]-nums[0]*nums[1]; - - // option 2 O(n) time O(1) space - int lm = 0, rm = 0; - int lmin = 10001, rmin = 10001; - int l = 0, r = nums.size() - 1; - while (l < r) - { - lm = max(lm, nums[l]); - rm = max(rm, nums[r]); - if (nums[l] >= nums[r]) - r--; - else - l++; - } - - l = 0; - r = nums.size() - 1; - while (l < r) - { - lmin = min(lmin, nums[l]); - rmin = min(rmin, nums[r]); - if (nums[l] <= nums[r]) - r--; - else - l++; - } - cout << lm << " " << rm << " " << lmin << " " << rmin << endl; - return lm * rm - lmin * rmin; - } -}; \ No newline at end of file diff --git a/C_plus/191_NumberOf1Bits.cpp b/C_plus/191_NumberOf1Bits.cpp deleted file mode 100644 index d33ae26..0000000 --- a/C_plus/191_NumberOf1Bits.cpp +++ /dev/null @@ -1,32 +0,0 @@ -class Solution -{ -public: - int hammingWeight(uint32_t n) - { - - // bit manipulation can avoid overflow - // option 1 - // int ret = 0; - // for (int i = 0; i < 32; ++i) - // { - // ret += (n % 2); - // n = n >> 1; - // } - // option 1.2 bitwise - // int ret = 0; - // while(n){ - // ret += (n&1); - // n >>=1; // n = n>>1; - // } - // return ret; - - // option 2 make use of n & (n-1)=0 可以將最低位的1消除 - int ret = 0; - while (n) - { - ret ++; - n = n & (n - 1); - } - return ret; - } -}; \ No newline at end of file diff --git a/C_plus/195_TenthLine.sh b/C_plus/195_TenthLine.sh deleted file mode 100644 index dd24dd7..0000000 --- a/C_plus/195_TenthLine.sh +++ /dev/null @@ -1,4 +0,0 @@ - -# Read from the file file.txt and output the tenth line to stdout. - -head -n 10 file.txt | tail -n +10 \ No newline at end of file diff --git a/C_plus/198_HouseRobber.cpp b/C_plus/198_HouseRobber.cpp deleted file mode 100644 index 3c38eb7..0000000 --- a/C_plus/198_HouseRobber.cpp +++ /dev/null @@ -1,37 +0,0 @@ -class Solution -{ -public: - int rob(vector &nums) - { - // 1 2 3 1 - // 1 2 4 4 - // option 1 dp - // int n = nums.size(); - // if(n==1) return nums[0]; - // vector dp(n,0); - // dp[0] = nums[0]; - // dp[1] = max(nums[1], dp[0]); - // for(int i =2;i rightSideView(TreeNode *root) - { - if (!root) - return {}; - vector ret; - // level traverse - queue q; - q.push(root); - while (!q.empty()) - { - ret.push_back(q.back()->val); - - int size = q.size(); - for (int i = 0; i < size; ++i) - { - TreeNode *cur = q.front(); - q.pop(); - - if (cur->left) - q.push(cur->left); - if (cur->right) - q.push(cur->right); - } - } - return ret; - } -}; \ No newline at end of file diff --git a/C_plus/19_RemoveNthNodeFromEndOfList.cpp b/C_plus/19_RemoveNthNodeFromEndOfList.cpp deleted file mode 100644 index aee31f4..0000000 --- a/C_plus/19_RemoveNthNodeFromEndOfList.cpp +++ /dev/null @@ -1,71 +0,0 @@ -/** - * Definition for singly-linked list. - * struct ListNode { - * int val; - * ListNode *next; - * ListNode() : val(0), next(nullptr) {} - * ListNode(int x) : val(x), next(nullptr) {} - * ListNode(int x, ListNode *next) : val(x), next(next) {} - * }; - */ -class Solution -{ -public: - ListNode *removeNthFromEnd(ListNode *head, int n) - { - // option 1 two pointer 不知道串列長度 iterative - // ListNode *fast = new ListNode(0), *slow = fast, *ret = slow; - // fast->next = head; - // while (n) - // { - // fast = fast->next; - // n--; - // } - - // while (fast->next) - // { - // slow = slow->next; - // fast = fast->next; - // } - - // slow->next = slow->next->next; - // return ret->next; - - // option 1.1 不額外使用space - // ListNode *slow , *fast ; - // slow = fast = head; - - // // 會先做 n>0 再 n-- - // while(n-- >0) fast = fast->next; - - // // 表示刪除鏈接串列的頭 - // if(fast == nullptr) return head->next; - - // while(fast && fast->next){ - // slow = slow->next; - // fast = fast->next; - // } - - // slow->next = slow->next->next; - - // return head; - - // option 2 Recursive - int curr = -1; - return helper(head, n, curr); - } - ListNode *helper(ListNode *node, int &n, int &curr) - { - if (!node) - { - curr = 0; - return NULL; - } - node->next = helper(node->next, n, curr); - if (++curr == n) - { - return node->next; - } - return node; - } -}; \ No newline at end of file diff --git a/C_plus/1_TwoSum.cpp b/C_plus/1_TwoSum.cpp deleted file mode 100644 index 8c6d562..0000000 --- a/C_plus/1_TwoSum.cpp +++ /dev/null @@ -1,54 +0,0 @@ -class TwoSum -{ -private: - set freq; - list nums; - -public: - void add(int number) - { - // 紀錄所有可能組了的和 - for (int n : nums) - { - freq.insert(n + number); - } - nums.push_back(number); - } - // 設計API,應該考慮find可能被運行多次,不可能每次都要O(N),優化成O(1) - bool find(int value) - { - return freq.count(value); - } -}; - -class Solution -{ - -public: - vector twoSum(vector &nums, int target) - { - // https://web.stanford.edu/class/cs9/sample_probs/TwoSum.pdf - - // option 1 brute O(n^2) time and O(1) space - // int n = nums.size(); - // for(int i=0;i mp; - int n = nums.size(); - for(int i=0;i > &grid, int i, int j, vector > &visit) - { - int m = grid.size(), n = grid[0].size(); - if (i < 0 || j < 0 || i >= m || j >= n || visit[i][j] || grid[i][j] == '0') - return; - - visit[i][j] = true; - isLand(grid, i - 1, j, visit); - isLand(grid, i + 1, j, visit); - isLand(grid, i, j - 1, visit); - isLand(grid, i, j + 1, visit); - } - int numIslands(vector > &grid) - { - int m = grid.size(), n = grid[0].size(); - vector > visit(m, vector(n)); - int ret = 0; - for (int i = 0; i < m; ++i) - { - for (int j = 0; j < n; ++j) - { - if (grid[i][j] == '0' || visit[i][j]) - continue; - ret++; - isLand(grid, i, j, visit); - } - } - - return ret; - } -}; - - - -// option 2 -void dfs(vector>& grid, int i, int j){ - int n = grid.size(), m = grid[0].size(); - if(i<0 || j<0 || i>n-1 || j>m-1 || grid[i][j]=='0') return; - - grid[i][j] = '0'; - dfs(grid, i-1,j); - dfs(grid, i,j-1); - dfs(grid, i+1,j); - dfs(grid, i,j+1); - - } - int numIslands(vector>& grid) { - int cnt = 0; - int n = grid.size(), m = grid[0].size(); - for(int i=0;i>= 1; - left >>= 1; - count++; - } - return right << count; - } -}; \ No newline at end of file diff --git a/C_plus/202_HappyNumber.cpp b/C_plus/202_HappyNumber.cpp deleted file mode 100644 index 2a3523c..0000000 --- a/C_plus/202_HappyNumber.cpp +++ /dev/null @@ -1,45 +0,0 @@ -class Solution -{ -public: - int Nextnum(int n) - { - int sum = 0; - while (n) - { - sum += (n % 10) * (n % 10); - n /= 10; - } - return sum; - } - bool isHappy(int n) - { - - //option 1 two pointer slow and fast - // int slow =n, fast =n; - // while(1){ - // slow = Nextnum(slow); - // fast = Nextnum(fast); - // fast = Nextnum(fast); - // if(slow==1) return true; - // if(fast == slow) break; - - // } - // return false; - - // option 2 use set to record alreay seen - int m = n; - set s; - while (m) - { - - int sum = Nextnum(m); - m = sum; - if (s.find(m) != s.end()) - break; - s.insert(m); - if (m == 1) - return true; - } - return false; - } -}; \ No newline at end of file diff --git a/C_plus/203_RemoveLinkedListElements.cpp b/C_plus/203_RemoveLinkedListElements.cpp deleted file mode 100644 index 6bc6166..0000000 --- a/C_plus/203_RemoveLinkedListElements.cpp +++ /dev/null @@ -1,50 +0,0 @@ -/** - * Definition for singly-linked list. - * struct ListNode { - * int val; - * ListNode *next; - * ListNode() : val(0), next(nullptr) {} - * ListNode(int x) : val(x), next(nullptr) {} - * ListNode(int x, ListNode *next) : val(x), next(next) {} - * }; - */ -class Solution -{ -public: - ListNode *removeElements(ListNode *head, int val) - { - // - if (head == nullptr) - return head; - ListNode *dummy = new ListNode(-1), *p = dummy; - p->next = head; - - while (p->next) - { - if (p->next->val == val) - { - p->next = p->next->next; - } - else - p = p->next; - } - return dummy->next; - - // slow fast pointer - ListNode *ret = new ListNode(-1); - ret->next = head; - ListNode *slow = ret, *fast = head; - - while (fast) - { - if (fast->val == val) - { - slow->next = fast->next; - } - else - slow = slow->next; - fast = fast->next; - } - return ret->next; - } -}; \ No newline at end of file diff --git a/C_plus/204_CountPrimes.cpp b/C_plus/204_CountPrimes.cpp deleted file mode 100644 index 364ca7a..0000000 --- a/C_plus/204_CountPrimes.cpp +++ /dev/null @@ -1,51 +0,0 @@ -class Solution -{ -public: - int countPrimes(int n) - { - // option 1 , - // 仍存在重複計算 i = 4, 4*2 =8, 4*3 =12, - // 但這兩個數字已經在 i= 2 和 i=3 的 2*4 3*4 倍標記了 - // vector visited(n, true); - - // for(int i=2;i*i visited(n, true); - - for (int i = 2; i <= n / i; ++i) - { - if (visited[i]) - { - for (int j = i * i; j < n; j += i) // 這樣比較快 - { - visited[j] = false; - } - } - } - int ret = 0; - for (int i = 2; i < n; ++i) - { - if (visited[i]) - ret++; - } - return ret; - } - - // option 3 -}; \ No newline at end of file diff --git a/C_plus/2057_SmallestIndexWithEqualValue.cpp b/C_plus/2057_SmallestIndexWithEqualValue.cpp deleted file mode 100644 index c3bf127..0000000 --- a/C_plus/2057_SmallestIndexWithEqualValue.cpp +++ /dev/null @@ -1,15 +0,0 @@ -class Solution -{ -public: - int smallestEqual(vector &nums) - { - // O(n) time - int n = nums.size(); - for (int i = 0; i < n; ++i) - { - if (i % 10 == nums[i]) - return i; - } - return -1; - } -}; \ No newline at end of file diff --git a/C_plus/2058_FindtheMinimumandMaximumNumberofNodesBetweenCriticalPoints.cpp b/C_plus/2058_FindtheMinimumandMaximumNumberofNodesBetweenCriticalPoints.cpp deleted file mode 100644 index 5ad6e6f..0000000 --- a/C_plus/2058_FindtheMinimumandMaximumNumberofNodesBetweenCriticalPoints.cpp +++ /dev/null @@ -1,65 +0,0 @@ -/** - * Definition for singly-linked list. - * struct ListNode { - * int val; - * ListNode *next; - * ListNode() : val(0), next(nullptr) {} - * ListNode(int x) : val(x), next(nullptr) {} - * ListNode(int x, ListNode *next) : val(x), next(next) {} - * }; - */ -class Solution -{ -public: - vector nodesBetweenCriticalPoints(ListNode *head) - { - - // O(n) time - int local_min = INT_MAX, local_max = INT_MIN; - - vector ret(2, -1); - if (!head || !head->next || !head->next->next) - return ret; - ListNode *pre = head, *cur = head->next, *post = head->next->next; - // vector> collect; - vector nums; - int i = 1; - while (post) - { - if (cur->val > pre->val && cur->val > post->val) - { - local_max = max(local_max, cur->val); - // collect.push_back(make_pair(cur, i)); - nums.push_back(i); - } - else if (cur->val < pre->val && cur->val < post->val) - { - local_min = min(local_min, cur->val); - // collect.push_back(make_pair(cur, i)); - nums.push_back(i); - } - - i++; - pre = cur; - cur = post; - post = post->next; - } - - if (nums.empty() || nums.size() == 1) - return {-1, -1}; - for (int n : nums) - cout << n << " "; - // given increase arr , to find max diff and min diff - // 2 4 5 => 1,3 - // 1 4 => 3,3 - // - int minDistance = INT_MAX, maxDistance = INT_MIN; - maxDistance = nums.back() - nums.front(); - for (int i = 1; i < nums.size(); ++i) - { - minDistance = min(minDistance, nums[i] - nums[i - 1]); - } - - return {minDistance, maxDistance}; - } -}; \ No newline at end of file diff --git a/C_plus/2059*_MinimumOperationstoConvertNumber.cpp b/C_plus/2059*_MinimumOperationstoConvertNumber.cpp deleted file mode 100644 index a3d51b9..0000000 --- a/C_plus/2059*_MinimumOperationstoConvertNumber.cpp +++ /dev/null @@ -1,51 +0,0 @@ -class Solution -{ -public: - int minimumOperations(vector &nums, int start, int goal) - { - // BFS => time limit - vector visited(1001, false); - queue q; - q.push(start); - visited[start] = true; - int step = 0; - while (!q.empty()) - { - step++; - int size = q.size(); - for (int i = 0; i < size; ++i) - { - int p = q.front(); - q.pop(); - for (int n : nums) - { - int temp = p + n; - if (temp == goal) - return step; - if (temp >= 0 && temp <= 1000 && !visited[temp]) - { - q.push(temp); - visited[temp] = true; - } - temp = p - n; - if (temp == goal) - return step; - if (temp >= 0 && temp <= 1000 && !visited[temp]) - { - q.push(temp); - visited[temp] = true; - } - temp = p ^ n; - if (temp == goal) - return step; - if (temp >= 0 && temp <= 1000 && !visited[temp]) - { - q.push(temp); - visited[temp] = true; - } - } - } - } - return -1; - } -}; \ No newline at end of file diff --git a/C_plus/205_IsomorphicStrings.cpp b/C_plus/205_IsomorphicStrings.cpp deleted file mode 100644 index e7870fc..0000000 --- a/C_plus/205_IsomorphicStrings.cpp +++ /dev/null @@ -1,28 +0,0 @@ -class Solution -{ -public: - bool isIsomorphic(string s, string t) - { - // option 1 use map - // map m1, m2; - // for(int i=0;i his(5, 0); - for (char c : word) - { - if (c == 'a') - his[0]++; - else if (c == 'e') - his[1]++; - else if (c =1306. Jump Game III= 'i') - his[2]++; - else if (c == 'o') - his[3]++; - else if (c == 'u') - his[4]++; - else - return false; - } - for (int h : his) - { - if (h == 0) - return false; - } - return true; - } - int countVowelSubstrings(string word) - { - // O(n^2*m) time - int cnt = 0; - int n = word.size(); - for (int i = 0; i < n; ++i) - { - bool first = true; - for (int j = i; j < n; ++j) - { - string temp = word.substr(i, j - i + 1); - if (isValid(temp)) - cnt++; - } - } - return cnt; - } -}; \ No newline at end of file diff --git a/C_plus/2063_VowelsofAllSubstrings.cpp b/C_plus/2063_VowelsofAllSubstrings.cpp deleted file mode 100644 index 9d93b52..0000000 --- a/C_plus/2063_VowelsofAllSubstrings.cpp +++ /dev/null @@ -1,17 +0,0 @@ -class Solution -{ -public: - long long countVowels(string word) - { - long long cnt = 0, ans = 0, n = word.size(); - for (char c : word) - { - ++cnt; - if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') - { - ans += cnt * (n - cnt + 1); - } - } - return ans; - } -}; \ No newline at end of file diff --git a/C_plus/2068_CheckWhetherTwoStringsareAlmostEquivalent.cpp b/C_plus/2068_CheckWhetherTwoStringsareAlmostEquivalent.cpp deleted file mode 100644 index 95ae98c..0000000 --- a/C_plus/2068_CheckWhetherTwoStringsareAlmostEquivalent.cpp +++ /dev/null @@ -1,17 +0,0 @@ -class Solution { -public: - bool checkAlmostEquivalent(string word1, string word2) { - - int cnt = 0; - int n = word1.size(); - vector his1(26,0), his2(26,0); - for(int i=0;i3) return false; - } - return true; - } -}; \ No newline at end of file diff --git a/C_plus/2069*_WalkingRobotSimulationII.cpp b/C_plus/2069*_WalkingRobotSimulationII.cpp deleted file mode 100644 index a5a6134..0000000 --- a/C_plus/2069*_WalkingRobotSimulationII.cpp +++ /dev/null @@ -1,54 +0,0 @@ -class Robot -{ -private: - int width, height, dir; - vector dirs = {"East", "North", "West", "South"}; - vector cur; - vector > acts = { - {1, 0}, {0, 1}, {-1, 0}, {0, -1}}; - -public: - Robot(int width, int height) - { - this->width = width; - this->height = height; - dir = 0; - cur = vector(2, 0); - } - void move() - { - int x = cur[0] + acts[dir % 4][0]; - int y = cur[1] + acts[dir % 4][1]; - while (x < 0 || x > width - 1 || y < 0 || y > height - 1) - { - dir++; - x = cur[0] + acts[dir % 4][0]; - y = cur[1] + acts[dir % 4][1]; - } - cur[0] = x; - cur[1] = y; - } - void step(int num) - { - for (int i = 0; i < num; ++i) - move(); - } - - vector getPos() - { - return cur; - } - - string getDir() - { - return dirs[dir % 4]; - } -}; - -/** - * Your Robot object will be instantiated and called as such: - * Robot* obj = new Robot(width, height); - * obj->step(num); - * vector param_2 = obj->getPos(); - * string param_3 = obj->getDir(); - */ \ No newline at end of file diff --git a/C_plus/206_ReverseLinkedList.cpp b/C_plus/206_ReverseLinkedList.cpp deleted file mode 100644 index 033577c..0000000 --- a/C_plus/206_ReverseLinkedList.cpp +++ /dev/null @@ -1,63 +0,0 @@ -/** - * Definition for singly-linked list. - * struct ListNode { - * int val; - * ListNode *next; - * ListNode() : val(0), next(nullptr) {} - * ListNode(int x) : val(x), next(nullptr) {} - * ListNode(int x, ListNode *next) : val(x), next(next) {} - * }; - */ -class Solution -{ -public: - ListNode *reverseList(ListNode *head) - { - // option 1 iterative - - // if(!head || !head->next) return head; - // ListNode *pre = nullptr, *cur = head, *post = head->next; - // while(post){ - // // 實施反轉 - // cur->next = pre; - // // 置位 - // pre = cur; - // cur = post; - // post = post->next; - // } - - // cur->next = pre; - // head = cur; - // return head; - - // option 1 version 2 - - // if(!head || !head->next) return head; - // ListNode *pre = new ListNode(-1), *cur = head; - // pre->next = cur; - // ListNode * temp ; - // while(cur->next){ - // temp = cur->next; - // // 下次temp的位置先儲存起來 - // cur->next = temp->next; - // // 實施反轉 - // temp->next = pre->next; - // // 確保pre的next為反轉後的頭head - // pre->next = temp; - // } - // head = temp; - // return head; - - // option 2 recursive - // 防止輸入為空鏈接串列 - if (head == nullptr) - return head; - if (head->next == nullptr) - return head; - ListNode *node = reverseList(head->next); - // 利用call function 天然的stack性質 - head->next->next = head; - head->next = nullptr; - return node; - } -}; \ No newline at end of file diff --git a/C_plus/207*_CourseSchedule.cpp b/C_plus/207*_CourseSchedule.cpp deleted file mode 100644 index 288b43b..0000000 --- a/C_plus/207*_CourseSchedule.cpp +++ /dev/null @@ -1,55 +0,0 @@ -class Solution -{ -public: - vector visited; - vector onPath; - bool hasCycle = false; - void traverse(vector > &graph, int s) - { - if (onPath[s]) - { - hasCycle = true; - return; - } - if (visited[s]) - return; - // pre-order - // 將節點 標記已遍歷 - visited[s] = true; - // 開始遍歷節點 - onPath[s] = true; - - for (int to : graph[s]) - { - traverse(graph, to); - } - onPath[s] = false; - } - bool canFinish(int numCourses, vector > &prerequisites) - { - // Graph - // topological Sort 有向無環圖 - - // prerequisites = [[3,0],[3,1],[6,3],[7,3],[5,4],[9,5],[9,7]] - vector > graph(numCourses); // 相鄰串列 - - for (auto edge : prerequisites) - { - int from = edge[1]; - int to = edge[0]; - graph[from].push_back(to); - } - - // 檢查圖是否有環 - visited = vector(numCourses, false); - onPath = vector(numCourses, false); - for (int i = 0; i < numCourses; ++i) - { - // 因為可能不是所有節點都有相連 - traverse(graph, i); - } - for (bool b : visited) - cout << b << " "; - return !hasCycle; - } -}; \ No newline at end of file diff --git a/C_plus/2078_TwoFurthestHousesWithDifferentColors.cpp b/C_plus/2078_TwoFurthestHousesWithDifferentColors.cpp deleted file mode 100644 index 0d3ecca..0000000 --- a/C_plus/2078_TwoFurthestHousesWithDifferentColors.cpp +++ /dev/null @@ -1,19 +0,0 @@ -class Solution -{ -public: - int maxDistance(vector &colors) - { - - int res = 0; - int n = colors.size(); - for (int i = 0; i < n - 1; ++i) - { - for (int j = i + 1; j < n; ++j) - { - if (colors[i] != colors[j]) - res = max(res, j - i); - } - } - return res; - } -}; \ No newline at end of file diff --git a/C_plus/208*_ImplementTrie(PrefixTree).cpp b/C_plus/208*_ImplementTrie(PrefixTree).cpp deleted file mode 100644 index 5234e92..0000000 --- a/C_plus/208*_ImplementTrie(PrefixTree).cpp +++ /dev/null @@ -1,74 +0,0 @@ -class TrieNode -{ -public: - TrieNode *child[26]; - bool isWord; - TrieNode() : isWord(false) - { - for (auto &a : child) - a = nullptr; - } -}; - -class Trie -{ -private: - TrieNode *root; - -public: - /** Initialize your data structure here. */ - Trie() - { - root = new TrieNode(); - } - - /** Inserts a word into the trie. */ - void insert(string word) - { - TrieNode *p = root; - for (auto &c : word) - { - int i = c - 'a'; - if (!p->child[i]) - p->child[i] = new TrieNode(); - p = p->child[i]; - } - p->isWord = true; - } - - /** Returns if the word is in the trie. */ - bool search(string word) - { - TrieNode *p = root; - for (char c : word) - { - int i = c - 'a'; - if (p->child[i] == nullptr) - return false; - p = p->child[i]; - } - return p->isWord; - } - - /** Returns if there is any word in the trie that starts with the given prefix. */ - bool startsWith(string prefix) - { - TrieNode *p = root; - for (char c : prefix) - { - int i = c - 'a'; - if (p->child[i] == nullptr) - return false; - p = p->child[i]; - } - return true; - } -}; - -/** - * Your Trie object will be instantiated and called as such: - * Trie* obj = new Trie(); - * obj->insert(word); - * bool param_2 = obj->search(word); - * bool param_3 = obj->startsWith(prefix); - */ \ No newline at end of file diff --git a/C_plus/209_MinimumSizeSubarraySum.cpp b/C_plus/209_MinimumSizeSubarraySum.cpp deleted file mode 100644 index c0801e3..0000000 --- a/C_plus/209_MinimumSizeSubarraySum.cpp +++ /dev/null @@ -1,30 +0,0 @@ -class Solution -{ -public: - int minSubArrayLen(int target, vector &nums) - { - - // O(n) time sliding window - int l = 0, r = 0; - int ret = INT_MAX; - int window = 0; - while (r < nums.size()) - { - int c = nums[r++]; - - window += c; - while (window >= target) - { - - if (window >= target) - { - ret = min(ret, r - l); - } - - int d = nums[l++]; - window -= d; - } - } - return ret == INT_MAX ? 0 : ret; - } -}; \ No newline at end of file diff --git a/C_plus/20_ValidParenthese.cpp b/C_plus/20_ValidParenthese.cpp deleted file mode 100644 index 192ea3f..0000000 --- a/C_plus/20_ValidParenthese.cpp +++ /dev/null @@ -1,29 +0,0 @@ -class Solution -{ -public: - bool isValid(string s) - { - - stack sta; - for (char c : s) - { - if (c == '(' || c == '[' || c == '{') - sta.push(c); - - else - { - if (sta.empty()) - return false; - else if (c == ')' && sta.top() == '(') - sta.pop(); - else if (c == ']' && sta.top() == '[') - sta.pop(); - else if (c == '}' && sta.top() == '{') - sta.pop(); - else - return false; - } - } - return sta.empty(); - } -}; \ No newline at end of file diff --git a/C_plus/210*_CourseScheduleII.cpp b/C_plus/210*_CourseScheduleII.cpp deleted file mode 100644 index 1aad9a0..0000000 --- a/C_plus/210*_CourseScheduleII.cpp +++ /dev/null @@ -1,89 +0,0 @@ -class Solution -{ -public: - vector visited; - vector onPath; - bool hasCycle = false; - - void traverse(vector > &graph, int s, vector &path) - { - - if (visited[s]) - return; - // cout< findOrder(int numCourses, vector > &prerequisites) - { - - // graph 建造 - vector > graph(numCourses); - - for (auto v : prerequisites) - { - int from = v[1]; - int to = v[0]; - graph[from].push_back(to); - } - - // 先檢測 圖是否有環 - - if (canFinish(numCourses, graph)) - return {}; - - // traverse - vector path; - visited = vector(numCourses, false); - for (int i = 0; i < numCourses; ++i) - { - traverse(graph, i, path); - } - - // 後序遍歷 + reverse 等於 拓樸排序 - reverse(path.begin(), path.end()); - return path; - } - bool canFinish(int numCourses, vector > &graph) - { - // 檢查圖是否有環 - visited = vector(numCourses, false); - onPath = vector(numCourses, false); - for (int i = 0; i < numCourses; ++i) - { - // 因為可能不是所有節點都有相連 - traverse(graph, i); - } - return hasCycle; - } - - void traverse(vector > &graph, int s) - { - if (onPath[s]) - { - hasCycle = true; - return; - } - if (visited[s]) - return; - // pre-order - // 將節點 標記已遍歷 - visited[s] = true; - // 開始遍歷節點 - onPath[s] = true; - - for (int to : graph[s]) - { - traverse(graph, to); - } - onPath[s] = false; - } -}; \ No newline at end of file diff --git a/C_plus/213*_HouseRobberII.cpp b/C_plus/213*_HouseRobberII.cpp deleted file mode 100644 index 9bcd5a4..0000000 --- a/C_plus/213*_HouseRobberII.cpp +++ /dev/null @@ -1,27 +0,0 @@ -class Solution { -public: - int rob(vector & nums, int start, int end){ - - int a = nums[start]; - if(end-start+1==1) return a; - int b = max(nums[start+1], a); - int ret = 0; - for(int i = start+2;i<=end;++i){ - ret = max(a+nums[i], b); - a = b; - b = ret; - } - return max(ret, b); - - - } - int rob(vector& nums) { - // option 1 因為只會發生兩種情況。 - // 從第一家開始搶,就不能搶第 n-1 - // 從第二家開始搶,就可以一直搶下去 - int n =nums.size(); - if(n==1) return nums[0]; - return max(rob(nums, 0, n-2), rob(nums, 1,n-1)); - - } -}; \ No newline at end of file diff --git a/C_plus/215_KthLargestElementInAnArray.cpp b/C_plus/215_KthLargestElementInAnArray.cpp deleted file mode 100644 index f32a5ec..0000000 --- a/C_plus/215_KthLargestElementInAnArray.cpp +++ /dev/null @@ -1,70 +0,0 @@ -class Solution -{ -public: - int findKthLargest(vector &nums, int k) - { - // option 1 - // O(nlogn) - // sort(nums.begin(), nums.end()); - // return nums[nums.size()-k]; - - // option 2 - // priority queue O(nlogn) - // priority_queue q(nums.begin(), nums.end()); - // int ret; - // while(k){ - // ret = q.top(); - // q.pop(); - // k--; - // } - // return ret; - - // option 3 quick sort + binary search - // O(N^2) worse case - // 將partition 函數當作binary search的函數 - shuffle(nums); // 防止quick sort 的 worse case 加上洗牌 O(N) - int lo = 0, hi = nums.size()-1; - k = nums.size() - k;// 轉化成找最小 - while(lo <=hi){ - int p = partition(nums, lo, hi); // 確保 index-p 在陣列中是第 p 的數字 - if(p< k) lo = p+1; - else if(p > k) hi = p-1; - else return nums[p]; - } - - return -1; - } - // leetcode 384 - void shuffle(vector & nums) { - - int n = nums.size(); - for(int i=0;i &nums, int l, int r) - { - int pivot = nums[r]; - int i = l - 1; - for (int j = l; j < r; ++j) - { - if (nums[j] < pivot) - { - // swap - i++; - swap(nums[j], nums[i]); - } - } - i++; - swap(nums[i], nums[r]); - return i; - } -}; \ No newline at end of file diff --git a/C_plus/216*_CombinationSumIII.cpp b/C_plus/216*_CombinationSumIII.cpp deleted file mode 100644 index bbd471a..0000000 --- a/C_plus/216*_CombinationSumIII.cpp +++ /dev/null @@ -1,31 +0,0 @@ -class Solution -{ -public: - void dfs(int k, int target, vector > &ret, vector &path, int l) - { - - if (target < 0) - return; - if (target == 0) - { - if (k == 0) - ret.push_back(path); - return; - } - - for (int i = l; i <= 9; ++i) - { - path.push_back(i); - dfs(k - 1, target - i, ret, path, i + 1); - path.pop_back(); - } - } - - vector > combinationSum3(int k, int n) - { - vector > ret; - vector path; - dfs(k, n, ret, path, 1); - return ret; - } -}; \ No newline at end of file diff --git a/C_plus/217_ContainsDuplicate.cpp b/C_plus/217_ContainsDuplicate.cpp deleted file mode 100644 index d6d2d3c..0000000 --- a/C_plus/217_ContainsDuplicate.cpp +++ /dev/null @@ -1,26 +0,0 @@ -class Solution -{ -public: - bool containsDuplicate(vector &nums) - { - - // O(nlogn) time and O(m) space - // unordered_set s; - // for(int n:nums){ - // if(s.count(n)) return true; - // s.insert(n); - // } - // return false; - - // O(nlogn) time and O(1) space - sort(nums.begin(), nums.end()); - int temp = nums[0]; - for (int i = 1; i < nums.size(); ++i) - { - if (temp == nums[i]) - return true; - temp = nums[i]; - } - return false; - } -}; \ No newline at end of file diff --git a/C_plus/219_ContainsDuplicateII.cpp b/C_plus/219_ContainsDuplicateII.cpp deleted file mode 100644 index 6d77493..0000000 --- a/C_plus/219_ContainsDuplicateII.cpp +++ /dev/null @@ -1,17 +0,0 @@ -class Solution -{ -public: - bool containsNearbyDuplicate(vector &nums, int k) - { - //option 1 - // O(nlogn) - map m; - for (int i = 0; i < nums.size(); ++i) - { - if (m.find(nums[i]) != m.end() && (i - m[nums[i]]) <= k) - return true; - m[nums[i]] = i; - } - return false; - } -}; \ No newline at end of file diff --git a/C_plus/21_MergeTwoSortedLists.cpp b/C_plus/21_MergeTwoSortedLists.cpp deleted file mode 100644 index 2119c6f..0000000 --- a/C_plus/21_MergeTwoSortedLists.cpp +++ /dev/null @@ -1,47 +0,0 @@ -/** - * Definition for singly-linked list. - * struct ListNode { - * int val; - * ListNode *next; - * ListNode() : val(0), next(nullptr) {} - * ListNode(int x) : val(x), next(nullptr) {} - * ListNode(int x, ListNode *next) : val(x), next(next) {} - * }; - */ -class Solution -{ -public: - ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) - { - if (l1 == NULL && l2 == NULL) - return NULL; - ListNode *ret = new ListNode(); - ListNode *p = ret; - - if (l1 == NULL) - return l2; - if (l2 == NULL) - return l1; - - while (l1 && l2) - { - ret->next = new ListNode(); - ret = ret->next; - if (l1->val < l2->val) - { - ret->val = l1->val; - l1 = l1->next; - } - else - { - ret->val = l2->val; - l2 = l2->next; - } - } - if (l1) - ret->next = l1; - if (l2) - ret->next = l2; - return p->next; - } -}; \ No newline at end of file diff --git a/C_plus/22*-GenerateParenthese.cpp b/C_plus/22*-GenerateParenthese.cpp deleted file mode 100644 index 88e6d91..0000000 --- a/C_plus/22*-GenerateParenthese.cpp +++ /dev/null @@ -1,29 +0,0 @@ -class Solution -{ -public: - void traverse(int r, int l, string path, vector &ret) - { - if (l > r || l < 0 || r < 0) - return; - if (l == 0 && r == 0) - { - ret.push_back(path); - return; - } - - path.push_back('('); - traverse(r, l - 1, path, ret); - path.pop_back(); - - path.push_back(')'); - traverse(r - 1, l, path, ret); - path.pop_back(); - } - vector generateParenthesis(int n) - { - vector ret; - string r = ""; - traverse(n, n, r, ret); - return ret; - } -}; \ No newline at end of file diff --git a/C_plus/220*_ContainsDuplicateIII.cpp b/C_plus/220*_ContainsDuplicateIII.cpp deleted file mode 100644 index b5a3ea2..0000000 --- a/C_plus/220*_ContainsDuplicateIII.cpp +++ /dev/null @@ -1,21 +0,0 @@ -class Solution -{ -public: - bool containsNearbyAlmostDuplicate(vector &nums, int k, int t) - { - - // option 1 runtime error - map m; // value mapping index - int j = 0; - for (int i = 0; i < nums.size(); ++i) - { - if (i - j > k) - m.erase(nums[j++]); - auto a = m.lower_bound((long long)nums[i] - t); - if (a != m.end() && abs(a->first - nums[i]) <= t) - return true; - m[nums[i]] = i; - } - return false; - } -}; \ No newline at end of file diff --git a/C_plus/221_MaximalSquare.cpp b/C_plus/221_MaximalSquare.cpp deleted file mode 100644 index d1de94a..0000000 --- a/C_plus/221_MaximalSquare.cpp +++ /dev/null @@ -1,33 +0,0 @@ -class Solution { -public: - int maximalSquare(vector>& matrix) { - int m = matrix.size(), n = matrix[0].size(); - vector> dp(m , vector(n,0)); - - for(int i =0;ileft) + countNodes(root->right); - - // option 2 O(logn * logn) , worse case O(N*logN) - // 求高度 - if (!root) - return 0; - - TreeNode *left = root, *right = root; - int hl = 0, hr = 0; - while (left) - { // O(logN) - left = left->left; - hl++; - } - while (right) - { // O(logN) - right = right->right; - hr++; - } - - // 代表此Complete binary tree 同時也是 Full binary tree - if (hr == hl) - return pow(2, hl) - 1; - // 如果左右高度不一樣,則按照普通二元樹的計算高度方式 - return 1 + countNodes(root->left) + countNodes(root->right); // O(N) - } -}; \ No newline at end of file diff --git a/C_plus/223_RectangleArea.cpp b/C_plus/223_RectangleArea.cpp deleted file mode 100644 index 3a5d39e..0000000 --- a/C_plus/223_RectangleArea.cpp +++ /dev/null @@ -1,41 +0,0 @@ -class Solution -{ -public: - bool isRectangleOverlap(vector &rec1, vector &rec2) - { - // 加等號 是因為To be clear, two rectangles that only touch at the corner or edges do not overlap. - if (rec1[2] <= rec2[0]) - return false; - if (rec1[0] >= rec2[2]) - return false; - if (rec1[1] >= rec2[3]) - return false; - if (rec1[3] <= rec2[1]) - return false; - return true; - } - - int computeArea(int ax1, int ay1, int ax2, int ay2, int bx1, int by1, int bx2, int by2) - { - - // overlap - vector rec1 = {ax1, ay1, ax2, ay2}; - vector rec2 = {bx1, by1, bx2, by2}; - if (isRectangleOverlap(rec1, rec2)) - { - // intersection - int inter_x1 = max(ax1, bx1); - int inter_x2 = min(ax2, bx2); - int inter_y1 = max(ay1, by1); - int inter_y2 = min(ay2, by2); - int intersection = (inter_y2 - inter_y1) * (inter_x2 - inter_x1); - int uion = (ay2 - ay1) * (ax2 - ax1) + (by2 - by1) * (bx2 - bx1); - return uion - intersection; - } - // not overlap - else - { - return (ay2 - ay1) * (ax2 - ax1) + (by2 - by1) * (bx2 - bx1); - } - } -}; \ No newline at end of file diff --git a/C_plus/224*_BasicCalculator.cpp b/C_plus/224*_BasicCalculator.cpp deleted file mode 100644 index 41a0dac..0000000 --- a/C_plus/224*_BasicCalculator.cpp +++ /dev/null @@ -1,88 +0,0 @@ -class Solution -{ -public: - int helper(vector &s) - { - stack stack; - - int rs = 0; - int sign = 1; - stack.push(1); - for (int i = 0; i < s.size(); i++) - { - if (s[i] == ' ') - continue; - else if (s[i] == '(') - { - stack.push(stack.top() * sign); - sign = 1; - } - else if (s[i] == ')') - stack.pop(); - else if (s[i] == '+') - sign = 1; - else if (s[i] == '-') - sign = -1; - else - { - int temp = s[i] - '0'; - // while (i + 1 < s.size() && isdigit(s[i + 1] )) - while (i < s.size() && s[i] >= '0') - temp = 10 * temp + s[i++] - '0'; - rs += sign * stack.top() * temp; - } - } - return rs; - } - int calculate(string s) - { - - // convert string to int - // int n = 0; - // for(char c:s){ - // n = 10* n + (c-'0'); - // } - - // vector ret(s.begin(), s.end()); - - // return helper(ret); - stack nums, ops; - int num = 0; - int rst = 0; - int sign = 1; - for (char c : s) - { - if (isdigit(c)) - { - if (num >= (INT_MAX) / 10) - num = INT_MAX; - else - num = num * 10 + c - '0'; - } - else - { - rst += sign * num; - num = 0; - if (c == '+') - sign = 1; - if (c == '-') - sign = -1; - if (c == '(') - { - nums.push(rst); - ops.push(sign); - rst = 0; - sign = 1; - } - if (c == ')' && ops.size()) - { - rst = ops.top() * rst + nums.top(); - ops.pop(); - nums.pop(); - } - } - } - rst += sign * num; - return rst; - } -}; \ No newline at end of file diff --git a/C_plus/225_ImplementStackUsingQueue.cpp b/C_plus/225_ImplementStackUsingQueue.cpp deleted file mode 100644 index f9a81c5..0000000 --- a/C_plus/225_ImplementStackUsingQueue.cpp +++ /dev/null @@ -1,54 +0,0 @@ -class MyStack -{ -public: - /** Initialize your data structure here. */ - queue q; - MyStack() - { - } - - /** Push element x onto stack. */ - void push(int x) - { - q.push(x); - } - - /** Removes the element on top of the stack and returns that element. */ - int pop() - { - int size = q.size(); - int ret; - size--; - while (size) - { - ret = q.front(); - q.pop(); - size--; - q.push(ret); - } - ret = q.front(); - q.pop(); - return ret; - } - - /** Get the top element. */ - int top() - { - return q.back(); - } - - /** Returns whether the stack is empty. */ - bool empty() - { - return q.empty(); - } -}; - -/** - * Your MyStack object will be instantiated and called as such: - * MyStack* obj = new MyStack(); - * obj->push(x); - * int param_2 = obj->pop(); - * int param_3 = obj->top(); - * bool param_4 = obj->empty(); - */ \ No newline at end of file diff --git a/C_plus/226_InvertBinaryTree.cpp b/C_plus/226_InvertBinaryTree.cpp deleted file mode 100644 index fccffa2..0000000 --- a/C_plus/226_InvertBinaryTree.cpp +++ /dev/null @@ -1,61 +0,0 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution -{ -public: - void swapChild(TreeNode *node) - { - - // base case - if (node == nullptr) - return; - - // option 1 preorder - // 當前這node要做的事情 - TreeNode *temp = node->left; - node->left = node->right; - node->right = temp; - - swapChild(node->left); - swapChild(node->right); - - // option 2 postorder faster than preorder - - // swapChild(node->left); - // swapChild(node->right); - // // 當前這node要做的事情 - // swap(node->left, node->right); - - // inorder 也是可以處理這問題,但不直觀。需拜訪兩次左子樹 - - // swapChild(node->left); - // TreeNode *temp = node->left; - // node->left = node->right; - // node->right = temp; - // swapChild(node->left); - } - TreeNode *invertTree(TreeNode *root) - { - // option 1 construct new tree - if (!root) - return root; - TreeNode *newroot = new TreeNode(root->val); - newroot->left = invertTree(root->right); - newroot->right = invertTree(root->left); - return newroot; - - // option 2 recursive - // DFS postorder in-place - // swapChild(root); - // return root; - } -}; diff --git a/C_plus/227*_BasicCalculatorII.cpp b/C_plus/227*_BasicCalculatorII.cpp deleted file mode 100644 index 9c8b7f8..0000000 --- a/C_plus/227*_BasicCalculatorII.cpp +++ /dev/null @@ -1,67 +0,0 @@ -class Solution -{ -public: - int helper(vector &s) - { - // O(N) time O(1) space - - stack sta; - - int num = 0; - char sign = '+'; - int idx = 0; - // while(s.size() > 0){ - - // char c = s.front(); - // s.erase(s.begin()); - while (idx < s.size()) - { - char c = s[idx++]; - - if (isdigit(c)) - { - num = 10 * num + int(c - '0'); - } - - // if( (!isdigit(c) && c!=' ') || (s.size()==0) ){ - if ((!isdigit(c) && c != ' ') || (s.size() == idx)) - { - - if (sign == '+') - { - sta.push(num); - } - else if (sign == '-') - { - sta.push(-num); - } - else if (sign == '*') - { - sta.top() = sta.top() * num; - } - else if (sign == '/') - { - sta.top() = (int)(sta.top() / float(num)); - } - num = 0; - sign = c; - } - } - - int sum_of_elems = 0; - while (!sta.empty()) - { - sum_of_elems += sta.top(); - sta.pop(); - } - - return sum_of_elems; - } - - int calculate(string s) - { - vector ret(s.begin(), s.end()); - - return helper(ret); - } -}; \ No newline at end of file diff --git a/C_plus/228_SummaryRanges.cpp b/C_plus/228_SummaryRanges.cpp deleted file mode 100644 index da3f0b3..0000000 --- a/C_plus/228_SummaryRanges.cpp +++ /dev/null @@ -1,29 +0,0 @@ -class Solution { -public: - vector summaryRanges(vector& nums) { - if(nums.empty()) return {}; - if(nums.size() ==1) return {to_string(nums[0])}; - - int n = nums.size(); - vector ret = {to_string(nums[0])}; - string out ; - for(int i =1;i majorityElement(vector &nums) - { - // option 1 cheat O(n) time and O(n) space - // vector ret; - // int times = 1+nums.size()/3; - // unordered_map m; - // for(int n:nums) m[n]++; - - // for(auto n:m){ - // if(n.second>=times) ret.emplace_back(n.first); - // } - // return ret; - - // option 2 O(n) time and O(1) space - // 多數投票算法 O(n) time and O(1) space - // 任意一數組出現次數大於 n/3 的數最多有兩個 - vector res; - int a = 0, b = 0, cnt1 = 0, cnt2 = 0, n = nums.size(); - for (int num : nums) - { - if (num == a) - cnt1++; - else if (num == b) - cnt2++; - else if (cnt1 == 0) - { - a = num; - cnt1 = 1; - } - else if (cnt2 == 0) - { - b = num; - cnt2 = 1; - } - else - { - cnt1--; - cnt2--; - } - } - - cnt1 = cnt2 = 0; - for (int num : nums) - { - if (num == a) - cnt1++; - else if (num == b) - cnt2++; - } - if (cnt1 > n / 3) - res.emplace_back(a); - if (cnt2 > n / 3) - res.emplace_back(b); - - return res; - } -}; \ No newline at end of file diff --git a/C_plus/230_KthSmallestElementInaBST.cpp b/C_plus/230_KthSmallestElementInaBST.cpp deleted file mode 100644 index f6176d6..0000000 --- a/C_plus/230_KthSmallestElementInaBST.cpp +++ /dev/null @@ -1,173 +0,0 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ - -struct MyTreeNode -{ - int val; - int size; - MyTreeNode *left; - MyTreeNode *right; - MyTreeNode(int x) : val(x), size(1), left(nullptr), right(nullptr) {} -}; - -class Solution -{ -private: - vector v; - int ret = 0, rank = 0; - -public: - void traverse(TreeNode *root) - { - // base case - if (!root) - return; - - // inorder - // L - traverse(root->left); - // V - v.push_back(root->val); - // R - traverse(root->right); - } - void traverse(TreeNode *root, priority_queue, greater > &pq) - { - - if (!root) - return; - traverse(root->left, pq); - pq.push(root->val); - traverse(root->right, pq); - } - void traverse(TreeNode *root, int k) - { - //base case - if (!root) - return; - - //inorder - // L - traverse(root->left, k); - - // V - rank++; - if (k == rank) - { - ret = root->val; - return; - } - // R - traverse(root->right, k); - } - int kthSmallest(TreeNode *root, int k) - { - // option 1 - // 因為是BST,inorder traverse 本身會是已排序的 - // traverse(root); - // return v[k-1]; - - // option 1.1 optimalize option 1 using one varialbe - // traverse(root, k); - // return ret; - - // option 1.2 STL priority queue algorithm - priority_queue, greater > pq; - - traverse(root, pq); - k--; - while (k) - { - pq.pop(); - k--; - } - return pq.top(); - - // option 1.3 divid and conquer - // preorder - // int cnt = count(root->left); - // if( k<=cnt) return kthSmallest(root->left, k); - // else if(k>cnt +1 ) return kthSmallest(root->right, k-cnt-1); - // return root->val; - - // option 2 iterative + stack support - int cnt = 0; - stack sta; - TreeNode *p = root; - while (p || !sta.empty()) - { - // L - while (p) - { - sta.push(p); - p = p->left; - } - p = sta.top(); - sta.pop(); - - // V - cnt++; - if (cnt == k) - return p->val; - - // R - p = p->right; - } - return 0; - - // option 3 高級寫法 - // 295. Find Median from Data Stream - // MyTreeNode *node = build(root); - // return helper(node, k); - } - int count(TreeNode *node) - { - if (!node) - return 0; - return count(node->left) + count(node->right) + 1; - } - MyTreeNode *build(TreeNode *root) - { - - if (!root) - return nullptr; - - // traverse - MyTreeNode *node = new MyTreeNode(root->val); - node->left = build(root->left); - node->right = build(root->right); - if (node->left) - node->size += node->left->size; - if (node->right) - node->size += node->right->size; - return node; - } - int helper(MyTreeNode *node, int k) - { - if (node->left) - { - int cnt = node->left->size; - if (k <= cnt) - return helper(node->left, k); - else if (k > cnt + 1) - return helper(node->right, k - 1 - cnt); - - return node->val; - } - else - { - if (k == 1) - return node->val; - return helper(node->right, k - 1); - } - } -}; \ No newline at end of file diff --git a/C_plus/231_PowerOfTwo.cpp b/C_plus/231_PowerOfTwo.cpp deleted file mode 100644 index 202093f..0000000 --- a/C_plus/231_PowerOfTwo.cpp +++ /dev/null @@ -1,56 +0,0 @@ -class Solution -{ -public: - bool isPowerOfTwo(int n) - { - // option 1 brute force - // use loop - // if(n<=0) return false; - // else if(n>0){ - // for(int i=2; i>=1; - // } - // return ret==1; - - //option 3.1 因為2的指數二進位 只會有一個1 的關係 - // bit-wise - // int ret = 0 ; - // if(n<=0) return false; - // while(n){ - // ret++; - // n = n &(n-1); - // } - // return ret==1; - - //option 4 - // make use of n&(n-1) 因為2的指數二進位 只會有一個1 的關係 - // 注意括號的優先級 - // if(n<=0) return false; - // return (n&(n-1)) == 0; - - // return (n>0) && (!((n-1)&n)); - - // option 5 - // tricky , 2^30 = 2147483648/2 = 1073741824 - // cout< 0) && (1073741824 % n == 0); - } -}; \ No newline at end of file diff --git a/C_plus/232_ImplementQueueusingStacks.cpp b/C_plus/232_ImplementQueueusingStacks.cpp deleted file mode 100644 index 8c6c932..0000000 --- a/C_plus/232_ImplementQueueusingStacks.cpp +++ /dev/null @@ -1,81 +0,0 @@ -class MyQueue -{ -private: - stack sta; - stack back; - -public: - /** Initialize your data structure here. */ - MyQueue() - { - } - - /** Push element x to the back of queue. */ - void push(int x) - { - sta.push(x); - } - - /** Removes the element from in front of queue and returns that element. */ - int pop() - { - if (sta.empty()) - return -1; - int size = sta.size(); - size--; - while (size) - { - int val = sta.top(); - back.push(val); - sta.pop(); - size--; - } - int ret = sta.top(); - sta.pop(); - while (!back.empty()) - { - int val = back.top(); - back.pop(); - sta.push(val); - } - return ret; - } - - /** Get the front element. */ - int peek() - { - int size = sta.size(); - size--; - while (size) - { - int val = sta.top(); - back.push(val); - sta.pop(); - size--; - } - int ret = sta.top(); - - while (!back.empty()) - { - int val = back.top(); - back.pop(); - sta.push(val); - } - return ret; - } - - /** Returns whether the queue is empty. */ - bool empty() - { - return sta.empty(); - } -}; - -/** - * Your MyQueue object will be instantiated and called as such: - * MyQueue* obj = new MyQueue(); - * obj->push(x); - * int param_2 = obj->pop(); - * int param_3 = obj->peek(); - * bool param_4 = obj->empty(); - */ \ No newline at end of file diff --git a/C_plus/233*_NumberofDigitOne.cpp b/C_plus/233*_NumberofDigitOne.cpp deleted file mode 100644 index e612e48..0000000 --- a/C_plus/233*_NumberofDigitOne.cpp +++ /dev/null @@ -1,46 +0,0 @@ -class Solution -{ -public: - int countDigitOne(int n) - { - // n= 13 , 1, 10, 11, 12, 13. => 6個1 - // option 1 - // time out - // int count = 0; - // for(int i=1;i<=n ;++i){ - // int a = i; - // while(a){ - // if(a%10 ==1) count++; - // a /=10; - // } - // } - // return count; - - // 觀察法 - // [1,9] => 1 - // [10,19] => 11 - // [20,29] => 1 - // [30,39] => 1 - // [40,49] => 1 - // [50,59] => 1 - // [60,69] => 1 - // [70,79] => 1 - // [80,89] => 1 - // [90,99] => 1 - // [100,109] => 11 - // [110, 119] => 21 - // [120,129] => 11 - - // [0,99] = 20 - // [100,199] = 120 ,120 = 100 +20因為100~199每個數字都是 1 開頭 - int ret = 0, a = 1, b = 1; - while (n > 0) - { - ret += (n + 8) / 10 * a + (n % 10 == 1) * b; - b += n % 10 * a; - a *= 10; - n /= 10; - } - return ret; - } -}; \ No newline at end of file diff --git a/C_plus/234_PalindromeLinkedList.cpp b/C_plus/234_PalindromeLinkedList.cpp deleted file mode 100644 index 4e3df9a..0000000 --- a/C_plus/234_PalindromeLinkedList.cpp +++ /dev/null @@ -1,114 +0,0 @@ -/** - * Definition for singly-linked list. - * struct ListNode { - * int val; - * ListNode *next; - * ListNode() : val(0), next(nullptr) {} - * ListNode(int x) : val(x), next(nullptr) {} - * ListNode(int x, ListNode *next) : val(x), next(next) {} - * }; - */ -class Solution -{ -private: - ListNode *left; -public: - bool isPalindrome(ListNode *head) - { - // option 1 stack O(n) time and O(n) space - // 1. 前半部push到stack,後半部pop stack並比較其值是否相同, - // 2. 整條list push 到stack,在比較也可以 - // if(!head || !head->next) return true; - // stack sta; - // int len = 0; - // for(ListNode *p=head;p;p=p->next) len++; - // int half = len/2; - // ListNode *p=head; - // while(half){ - // sta.push(p->val); - // p=p->next; - // half--; - // } - // if(len%2==1) p=p->next; - // while(p && !sta.empty()){ - // if(sta.top()!=p->val) return false; - // sta.pop(); - // p=p->next; - // } - // return true; - - // option 2 slow-fast 適合用在未知大小串列 O(n) time and O(1) space - // 1. 快慢指針決定中點 - // 2. 中點後的串列reverse 或是靠stack - // 3. 用兩指針,一個指向頭、另一個指向中點,遍歷並比較是否相同 - // if(!head || !head->next) return true; - // ListNode *slow = head, *fast = head; - // while(fast->next && fast->next->next){ - // slow = slow->next; - // fast = fast->next->next; - // } - - // ListNode *cur = slow, *post = slow->next, *pre = nullptr; - - // while(post){ - // cur->next = pre; - // pre = cur; - // cur = post; - // post = post->next; - // } - // cur->next = pre; - - // slow = cur; - // cur = head; - // while(slow->next){ - // if(cur->val != slow->val) return false; - // cur=cur->next; - // slow = slow->next; - // } - // return true; - - // option 3.2 slow-fast 適合用在未知大小串列 O(n) time and O(1) space - // if(!head || !head->next) return true; - // ListNode *slow = head , *fast = head, *pre; - // stack sta; - // while(fast && fast->next){ - // sta.push(slow->val); - // slow =slow->next; - // fast = fast->next->next; - // } - // if(fast!=nullptr) slow = slow->next; - // while(slow){ - // if(sta.top() !=slow->val) return false; - // sta.pop(); - // slow=slow->next; - // } - // return true; - - // option 4 reverse and compare O(n) time and O(n) space - // 1. new 一個reverse的串列 ,不斷的insert 串列的頭 - // 2. 比較兩者是否相同 - // ListNode *mirror = nullptr; - // for(ListNode *p=head;p;p=p->next){ - // ListNode *tmp = new ListNode(p->val); - // tmp->next = mirror; - // mirror = tmp; - // } - // for(ListNode *p=head, *q = mirror;p, q;p=p->next, q=q->next){ - // if(p->val !=q->val) return false; - // } - // return true; - - // option 5 recursive O(n) time and O(n) space - left = head; - return travese(head->next); - } - - bool travese(ListNode *right){ - if(right==nullptr) return true; - - bool ret = travese(right->next); - ret = ret && (right->val == left->val); - left = left->next; - return ret; - } -}; \ No newline at end of file diff --git a/C_plus/235*_LowestCommonAncestorofaBinarySearchTree.cpp b/C_plus/235*_LowestCommonAncestorofaBinarySearchTree.cpp deleted file mode 100644 index 8a79ca6..0000000 --- a/C_plus/235*_LowestCommonAncestorofaBinarySearchTree.cpp +++ /dev/null @@ -1,65 +0,0 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode(int x) : val(x), left(NULL), right(NULL) {} - * }; - */ - -class Solution -{ -public: - bool covers(TreeNode *root, TreeNode *p) - { - if (root == nullptr) - return false; - if (root == p) - return true; - return covers(root->left, p) || covers(root->right, p); - } - TreeNode *ancestorHelper(TreeNode *root, TreeNode *p, TreeNode *q) - { - if (root == nullptr || root == p || root == q) - return root; - - bool pIsOnLeft = covers(root->left, p); - bool qIsOnLeft = covers(root->left, q); - - if (pIsOnLeft != qIsOnLeft) - return root; - - TreeNode *childSide = pIsOnLeft ? root->left : root->right; - return ancestorHelper(childSide, p, q); - } - TreeNode *lowestCommonAncestor(TreeNode *root, TreeNode *p, TreeNode *q) - { - // take advantage of the proerty binary search tree - // option 1 recursive - // left->val < root->val < right->val - // if ((root -> val > p -> val) && (root -> val > q -> val)) { - // return lowestCommonAncestor(root -> left, p, q); - // } - // else if((root -> val < p -> val) && (root -> val < q -> val)){ - // return lowestCommonAncestor(root -> right, p, q); - // } - // return root; - - // option 2 iterative - // while (true) { - // if (p -> val < root -> val && q -> val val) { - // root = root -> left; - // } else if (p -> val > root -> val && q -> val > root -> val) { - // root = root -> right; - // } else { - // break; - // } - // } - // return root; - - // option 3 considering to binary tree - // if(!covers(root, p) || !covers(root, q)) return nullptr; - return ancestorHelper(root, p, q); - } -}; \ No newline at end of file diff --git a/C_plus/236*_LowestCommonAncestorofaBinarySearchTreeII.cpp b/C_plus/236*_LowestCommonAncestorofaBinarySearchTreeII.cpp deleted file mode 100644 index 2ba7732..0000000 --- a/C_plus/236*_LowestCommonAncestorofaBinarySearchTreeII.cpp +++ /dev/null @@ -1,61 +0,0 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode(int x) : val(x), left(NULL), right(NULL) {} - * }; - */ -class Solution -{ -public: - bool covers(TreeNode *root, TreeNode *p) - { - if (!root) - return false; - if (root == p) - return true; - return covers(root->left, p) || covers(root->right, p); - } - - TreeNode *ancestorHelper(TreeNode *root, TreeNode *p, TreeNode *q) - { - if (root == nullptr || root == p || root == q) - return root; - - bool pIsOnLeft = covers(root->left, p); - bool qIsOnLeft = covers(root->left, q); - if(pIsOnLeft != qIsOnLeft) return root; - TreeNode *childSide; - if(pIsOnLeft==false && qIsOnLeft == false) childSide = root->right; - if(pIsOnLeft==true && qIsOnLeft==true ) childSide = root->left; - - return ancestor(childSide, p,q); - } - TreeNode *lowestCommonAncestor(TreeNode *root, TreeNode *p, TreeNode *q) - { - // option 1 - // check exist in the tree - // if(!covers(root, p) || !covers(root, q)) return nullptr; - - // return ancestorHelper(root, p, q); - - // option 2 recursive postorder - if (root == nullptr) - return nullptr; - if (root == p || root == q) - return root; - - TreeNode *left = lowestCommonAncestor(root->left, p, q); - TreeNode *right = lowestCommonAncestor(root->right, p, q); - // 情況一, p q 都是在以root 為根的樹中 - if (left != nullptr && right != nullptr) - return root; - // 情況二,p q都不在以root為根的樹中 - if (left == nullptr && right == nullptr) - return nullptr; - // 情況三,如果p q只有其中一點 存在於root中,返回該點 - return left == nullptr ? right : left; - } -}; \ No newline at end of file diff --git a/C_plus/237_DeleteNodeInaLinkedList.cpp b/C_plus/237_DeleteNodeInaLinkedList.cpp deleted file mode 100644 index 3e17ead..0000000 --- a/C_plus/237_DeleteNodeInaLinkedList.cpp +++ /dev/null @@ -1,21 +0,0 @@ -/** - * Definition for singly-linked list. - * struct ListNode { - * int val; - * ListNode *next; - * ListNode(int x) : val(x), next(NULL) {} - * }; - */ -class Solution -{ -public: - void deleteNode(ListNode *node) - { - - // option 1 copy the next node's value and delete it. - node->val = node->next->val; - ListNode *delnode = node->next; - node->next = node->next->next; - delete delnode; - } -}; \ No newline at end of file diff --git a/C_plus/238_ProductOfArrayExceptSelf.cpp b/C_plus/238_ProductOfArrayExceptSelf.cpp deleted file mode 100644 index 43b5115..0000000 --- a/C_plus/238_ProductOfArrayExceptSelf.cpp +++ /dev/null @@ -1,35 +0,0 @@ -class Solution { -public: - vector productExceptSelf(vector& nums) { - // option 1 O(n) space O(n) time - // int m = nums.size(); - // vector left (m,1), right(m,1); - // for(int i =1;i=0;i--){ - // right[i] = right[i+1] * nums[i+1]; - // } - // vector ret(m,1); - // for(int i=0;i ret(m,1); - for(int i=1;i-1;--i){ - ret[i] = ret[i]*right; - right = right * nums[i]; - } - return ret; - - - } -}; \ No newline at end of file diff --git a/C_plus/239*_SlidingWindowMaximum.cpp b/C_plus/239*_SlidingWindowMaximum.cpp deleted file mode 100644 index b05e0c3..0000000 --- a/C_plus/239*_SlidingWindowMaximum.cpp +++ /dev/null @@ -1,158 +0,0 @@ -class Solution -{ -private: - struct MonotonicQueue - { - private: - list q; - - public: - void push(int n) - { // O(1) - while (!q.empty() && q.back() < n) - { - q.pop_back(); - } - q.push_back(n); - } - void pop(int n) - { // O(1) - if (n == q.front()) - { - q.erase(q.begin()); - } - } - int max() - { // O(1) - return q.front(); - } - }; - -public: - vector maxSlidingWindow(vector &nums, int k) - { - - // option 1 brute timeout O(nk) - // vector window(k,1); - // vector maxWindow ; - // int n= nums.size(); - // for(int i=0;i<=n-k;++i){ - // // vector inner product - // int local_mx = INT_MIN; - // for(int j=i;j ret; - if (n < k) - { - int _max = INT_MIN; - for (int i = 0; i < n; ++i) - { - _max = max(_max, nums[i]); - ret.push_back(_max); - } - return ret; - } - - queue window; - for (int r = 0; r < n; r++) - { - window.push(nums[r]); - if (r >= k - 1) - { - if (r != k - 1) - window.pop(); - // search queue local max - int size = window.size(), local_max = INT_MIN; - while (size) - { - local_max = max(window.front(), local_max); - window.push(window.front()); - window.pop(); - size--; - } - ret.push_back(local_max); - } - } - return ret; - - // option 2 O(nlogn) STL multiset 紅黑樹 插入 刪除 O(logn) - // vector maxWindow ; - // multiset st; - // int n=nums.size(); - // for (int i = 0; i < n; ++i){ - // // 找到 nums[i-k] 位置 在針對此位置刪除,可避免 刪除到重複的元素 - // if (i >= k) st.erase(st.find(nums[i - k])); - // st.insert(nums[i]); - // // cout<<*st.begin()<<" "<<*st.rbegin()<= k - 1) maxWindow.push_back(*st.rbegin()); - // //multiset 是 升序排列的 - - // } - - // return maxWindow; - - // option 3 priority queue = max-heap O(nlogn) - // priority_queue> q; - // vector maxWindow ; - // int n=nums.size(); - // for (int i = 0; i < n; ++i){ - // while(!q.empty() && q.top().second <= i - k) q.pop(); - // q.push({nums[i], i}); - // if( i>=k-1) maxWindow.emplace_back(q.top().first); - - // } - - // return maxWindow; - - // option 4 O(n) deque - // option 1 dequeue 回護他的頭 是最大值 - deque dq; - vector ret; - for (int i = 0; i < nums.size(); ++i) - { - while (!dq.empty() && nums[i] > dq.back()) - { - dq.pop_back(); - } - - dq.push_back(nums[i]); - - // 縮減左側 - if (i >= k && nums[i - k] == dq.front()) - dq.pop_front(); - - // 存入結果 - if (i >= k - 1) - ret.push_back(dq.front()); - } - - return ret; - - // option 5 monotonic queue - int n = nums.size(); - MonotonicQueue window; - vector ret; - - for (int i = 0; i < n; ++i) - { - window.push(nums[i]); - if (i >= k - 1) - { - - ret.push_back(window.max()); - window.pop(nums[i - k + 1]); - } - } - - return ret; - } -}; \ No newline at end of file diff --git a/C_plus/23_MergekSortedLists.cpp b/C_plus/23_MergekSortedLists.cpp deleted file mode 100644 index ddd16bf..0000000 --- a/C_plus/23_MergekSortedLists.cpp +++ /dev/null @@ -1,90 +0,0 @@ -/** - * Definition for singly-linked list. - * struct ListNode { - * int val; - * ListNode *next; - * ListNode() : val(0), next(nullptr) {} - * ListNode(int x) : val(x), next(nullptr) {} - * ListNode(int x, ListNode *next) : val(x), next(next) {} - * }; - */ -class Solution -{ -public: - ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) - { - - ListNode *ret = new ListNode(0), *p = ret; - - while (l1 && l2) - { - if (l1->val <= l2->val) - { - p->next = l1; - l1 = l1->next; - } - else - { - p->next = l2; - l2 = l2->next; - } - p = p->next; - } - - if (l1) - { - p->next = l1; - } - if (l2) - { - p->next = l2; - } - - return ret->next; - } - ListNode *mergeKLists(vector &lists) - { - //option 1 - // if(lists.empty()) return nullptr; - // ListNode *ret = lists[0]; - // for(int i =1;i1){ - // int k = (n+1)/2; - // for(int i=0;ival > b->val; - }; - priority_queue, decltype(cmp)> list(cmp); - for (ListNode *v : lists) - { - if (v) - list.push(v); - } - while (!list.empty()) - { - ListNode *cur = list.top(); - list.pop(); - ret->next = cur; - ret = ret->next; - if (cur->next) - list.push(cur->next); - } - return ans->next; - } -}; \ No newline at end of file diff --git a/C_plus/24*_SwapNodesinPairs.cpp b/C_plus/24*_SwapNodesinPairs.cpp deleted file mode 100644 index 6fd4688..0000000 --- a/C_plus/24*_SwapNodesinPairs.cpp +++ /dev/null @@ -1,39 +0,0 @@ -/** - * Definition for singly-linked list. - * struct ListNode { - * int val; - * ListNode *next; - * ListNode() : val(0), next(nullptr) {} - * ListNode(int x) : val(x), next(nullptr) {} - * ListNode(int x, ListNode *next) : val(x), next(next) {} - * }; - */ -class Solution -{ -public: - ListNode *swapPairs(ListNode *head) - { - // option 1 modify value - // ListNode *cur = head; - // while(cur && cur->next){ - // int val = cur->val; - // cur->val = cur->next->val; - // cur->next->val = val; - // cur=cur->next->next; - // } - // return head; - - // option 2 - ListNode *dummy = new ListNode(-1), *pre = dummy; - dummy->next = head; - while (pre->next && pre->next->next) - { - ListNode *t = pre->next->next; - pre->next->next = t->next; - t->next = pre->next; - pre->next = t; - pre = t->next; - } - return dummy->next; - } -}; \ No newline at end of file diff --git a/C_plus/240_Searcha2DMatrixII.cpp b/C_plus/240_Searcha2DMatrixII.cpp deleted file mode 100644 index c121c6d..0000000 --- a/C_plus/240_Searcha2DMatrixII.cpp +++ /dev/null @@ -1,20 +0,0 @@ -class Solution -{ -public: - bool searchMatrix(vector > &matrix, int target) - { - int m = matrix.size(), n = matrix[0].size(); - - int i = m - 1, j = 0; - while (j <= n - 1 && i > -1) - { - if (matrix[i][j] == target) - return true; - else if (target > matrix[i][j]) - j++; - else - i--; - } - return false; - } -}; \ No newline at end of file diff --git a/C_plus/242_ValidAnagram.cpp b/C_plus/242_ValidAnagram.cpp deleted file mode 100644 index 56535e0..0000000 --- a/C_plus/242_ValidAnagram.cpp +++ /dev/null @@ -1,47 +0,0 @@ -class Solution -{ -public: - bool isAnagram(string s, string t) - { - // https://web.stanford.edu/class/cs9/sample_probs/Anagrams.pdf - - // option 1 sorted O(nlogn) - - // sort(s.begin(), s.end()); - // sort(t.begin(), t.end()); - // return s==t; - - // option 2 Counting O(n^2) time out - // if(s.size()!=t.size()) return false; - // for(char c:s){ - // if( countchar(c,s) != countchar(c,t)) return false; - // } - // return true; - - // improved option 2 Counting O(n) - if (s.size() != t.size()) - return false; - for (char c = 'a'; c <= 'z'; c++) - { - if (countchar(c, s) != countchar(c, t)) - return false; - } - return true; - - // option 3 Histogramming - // O(n) time and O(1) space - // vector vec(26,0); - // if(s.size()!=t.size()) return false; - // int n = s.size(); - // for(int i=0;i(26,0); - } - int countchar(char c, string s) - { - int ret = 0; - for (char cc : s) - ret += (c == cc) ? 1 : 0; - return ret; - } -}; \ No newline at end of file diff --git a/C_plus/25*_ReverseNodesink-Group.cpp b/C_plus/25*_ReverseNodesink-Group.cpp deleted file mode 100644 index 0222d0a..0000000 --- a/C_plus/25*_ReverseNodesink-Group.cpp +++ /dev/null @@ -1,86 +0,0 @@ -/** - * Definition for singly-linked list. - * struct ListNode { - * int val; - * ListNode *next; - * ListNode() : val(0), next(nullptr) {} - * ListNode(int x) : val(x), next(nullptr) {} - * ListNode(int x, ListNode *next) : val(x), next(next) {} - * }; - */ -class Solution -{ -public: - int getSize(ListNode *head) - { - int size = 0; - for (ListNode *p = head; p; p = p->next) - size++; - return size; - } - ListNode *getNextNode(ListNode *head, int k) - { - ListNode *p = head; - for (; k; k--) - p = p->next; - return p; - } - ListNode *reverse(ListNode *cur, ListNode *nextHead) - { - ListNode *pre = new ListNode(-1); - pre->next = cur; - while (cur->next != newHead) - { - ListNode *temp = cur->next; - cur->next = temp->next; - temp->next = pre->next; - pre->next = temp; - } - return pre->next; - } - ListNode *reverseKGroup(ListNode *head, int k) - { - // option 1 iterative - // if(!head->next) return head; - // int size = getSize(head); - // int reverseTime = size/k; - - // ListNode *cur=head, *pre = new ListNode(-1), *ret = pre; - // pre->next = head; - // // reverse unit - // while(reverseTime){ - // ListNode *nextHead = getNextNode(cur, k) ; - // // cout<<"nextHead:"<val<next !=nextHead){ - // temp = cur->next; - // cur->next = temp->next; - // temp->next = pre->next; - // pre->next = temp; - // } - // reverseTime--; - // pre = cur; - // cur = nextHead; - - // } - - // return ret->next; - - // option 2 recursive - if (head == nullptr) - return head; - ListNode *a = head, *b = head; - for (int i = 0; i < k; ++i) - { - // 鏈接串列長度不足k個 - if (b == nullptr) - return head; - b = b->next; - } - - // 反轉前k個元素 - ListNode *newHead = reverse(a, b); - a->next = reverseKGroup(b, k); - return newHead; - } -}; \ No newline at end of file diff --git a/C_plus/257*_BinaryTreePaths.cpp b/C_plus/257*_BinaryTreePaths.cpp deleted file mode 100644 index 90a8bc7..0000000 --- a/C_plus/257*_BinaryTreePaths.cpp +++ /dev/null @@ -1,37 +0,0 @@ -/* - * @Author: yuan - * @Date: 2021-07-16 15:32:44 - * @LastEditTime: 2021-07-16 16:16:42 - * @FilePath: /leet_code/C_plus/257*_BinaryTreePaths.cpp - */ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution { -public: - void path(TreeNode *root, vector & ret, string str){ - - - if(root->left) path(root->left, ret, str+"->" +to_string(root->left->val)); - if(root->right) path(root->right, ret, str+"->"+to_string(root->right->val)); - - if(root->left==nullptr && root->right==nullptr){ - ret.push_back(str); - } - - } - vector binaryTreePaths(TreeNode* root) { - // option 1 dfs - vector ret; - path(root, ret, to_string(root->val)); - return ret; - } -}; \ No newline at end of file diff --git a/C_plus/258_AddDigits.cpp b/C_plus/258_AddDigits.cpp deleted file mode 100644 index 8a3f48a..0000000 --- a/C_plus/258_AddDigits.cpp +++ /dev/null @@ -1,29 +0,0 @@ -class Solution -{ -public: - int addDigits(int num) - { - // option 1 - // int m = num; - // while(m>=10){ - - // int sum = 0; - // while(m){ - // sum += m%10; - // m/=10; - // } - // m=sum; - // } - // return m; - - // option 2 - // without any loop/recursion - // 1-9 => 1-9 - // 10-18 => 1-9 - // 19-27 => 1-9 - // 28-36 => 1-9 - if (n == 0) - return 0; - return (num - 1) % 9 + 1; - } -}; \ No newline at end of file diff --git a/C_plus/26*_RemoveDuplicatesFromSortedArray.cpp b/C_plus/26*_RemoveDuplicatesFromSortedArray.cpp deleted file mode 100644 index 2d89fda..0000000 --- a/C_plus/26*_RemoveDuplicatesFromSortedArray.cpp +++ /dev/null @@ -1,25 +0,0 @@ -class Solution -{ -public: - int removeDuplicates(vector &nums) - { - - if (nums.empty()) - return 0; - int slow = 0, fast = 0; - while (fast < nums.size()) - { - - if (nums[fast] != nums[slow]) - { - slow++; - // 維護nums[0...slow] 無重複就好 - nums[slow] = nums[fast]; - } - - fast++; - } - - return slow + 1; - } -}; \ No newline at end of file diff --git a/C_plus/260*_SingleNumberIII.cpp b/C_plus/260*_SingleNumberIII.cpp deleted file mode 100644 index 260429a..0000000 --- a/C_plus/260*_SingleNumberIII.cpp +++ /dev/null @@ -1,49 +0,0 @@ -class Solution -{ -public: - vector singleNumber(vector &nums) - { - - // option 1 O(n) time and O(n) space - set s; - for (int n : nums) - { - if (s.count(n)) - s.erase(n); - else - s.insert(n); - } - - vector ret; - for (int n : nums) - { - if (s.count(n)) - ret.push_back(n); - } - return ret; - - // option O(n) time and O(1) space - // 1. 將所有數字 xor,得到結果為那兩個單獨的數字的xor diff - // 2. 藉由 diff & -diff 去解出 那兩個數字 - - unsigned int diff = 0; - for (int n : nums) - diff ^= n; - diff &= -diff; - //-diff 110 => reverse bit and + 1 => 001 -> 010 - // set this diff bit to divide two part - vector ret(2, 0); - for (int a : nums) - { - if (a & diff) - { - ret[0] ^= a; - } - else - { - ret[1] ^= a; - } - } - return ret; - } -}; \ No newline at end of file diff --git a/C_plus/263_UglyNumber.cpp b/C_plus/263_UglyNumber.cpp deleted file mode 100644 index ca47d4f..0000000 --- a/C_plus/263_UglyNumber.cpp +++ /dev/null @@ -1,18 +0,0 @@ -class Solution -{ -public: - bool isUgly(int n) - { - if (n < 1) - return false; - int m = n; - - while (m % 5 == 0) - m /= 5; - while (m % 3 == 0) - m /= 3; - while (m % 2 == 0) - m /= 2; - return m == 1; - } -}; \ No newline at end of file diff --git a/C_plus/264*_UglyNumberII.cpp b/C_plus/264*_UglyNumberII.cpp deleted file mode 100644 index f64f3f0..0000000 --- a/C_plus/264*_UglyNumberII.cpp +++ /dev/null @@ -1,66 +0,0 @@ -class Solution -{ -public: - bool UglyNumber(int n) - { - while (n % 2 == 0) - n /= 2; - while (n % 3 == 0) - n /= 3; - while (n % 5 == 0) - n /= 5; - return n == 1; - } - int nthUglyNumber(int n) - { - // brute force => time out - // int cnt = 0, i=0; - // while(cnt, greater > pq; - pq.push(1); - for (int i = 1; i < n; ++i) - { - int t = pq.top(); - pq.pop(); - while (!pq.empty() && pq.top() == t) - pq.pop(); - if (t < INT_MAX / 2) - pq.push(t * 2); - if (t < INT_MAX / 3) - pq.push(t * 3); - if (t < INT_MAX / 5) - pq.push(t * 5); - } - return pq.top(); - - - // option 2 dp O(n) time - if(n <= 0) return false; // get rid of corner cases - if(n == 1) return true; // base case - vector dp(n, 0); - int t2 = 0, t3 = 0, t5 = 0; //pointers for 2, 3, 5 - - //2* 1 1 2 2 3 4 4 5 6 - //3* 0 1 1 1 2 2 3 3 4 - //5* 0 0 0 1 1 1 1 2 2 - //dp 2 3 4 5 6 8 9 10 12 - // - - dp[0] = 1; - for(int i=1;i &nums) - { - // option 1 O(n) time and O(n) space - - // int n =nums.size(); - // vector vec(n+1,false); - // for(int n:nums) vec[n]=true; - // for(int i=0;i mid) - right = mid; - else - left = mid + 1; - } - return right; - } -}; \ No newline at end of file diff --git a/C_plus/27*_RemoveElement.cpp b/C_plus/27*_RemoveElement.cpp deleted file mode 100644 index b5ce5e2..0000000 --- a/C_plus/27*_RemoveElement.cpp +++ /dev/null @@ -1,20 +0,0 @@ -class Solution -{ -public: - int removeElement(vector &nums, int val) - { - - int slow = 0, fast = 0; - while (fast < nums.size()) - { - - if (nums[fast] != val) - { - nums[slow] = nums[fast]; - slow++; - } - fast++; - } - return slow; - } -}; \ No newline at end of file diff --git a/C_plus/274_H-index.cpp b/C_plus/274_H-index.cpp deleted file mode 100644 index b86223e..0000000 --- a/C_plus/274_H-index.cpp +++ /dev/null @@ -1,14 +0,0 @@ -class Solution -{ -public: - int hIndex(vector &citations) - { - int count = 0, n = citations.size(); - sort(citations.begin(), citations.end(), greater<>()); - for (int i = 0; i < n; ++i) - { - count += (citations[i] >= i + 1) ? 1 : 0; - } - return count; - } -}; \ No newline at end of file diff --git a/C_plus/278_FirstBadVersion.cpp b/C_plus/278_FirstBadVersion.cpp deleted file mode 100644 index b6755bf..0000000 --- a/C_plus/278_FirstBadVersion.cpp +++ /dev/null @@ -1,22 +0,0 @@ -// The API isBadVersion is defined for you. -// bool isBadVersion(int version); - -class Solution -{ -public: - int firstBadVersion(int n) - { - // option 1 - // binary search - int l = 1, r = n; - while (l < r) - { - int mid = l + (r - l) / 2; - if (isBadVersion(mid)) - r = mid; - else - l = mid + 1; - } - return l; - } -}; \ No newline at end of file diff --git a/C_plus/279*_PerfectSquares.cpp b/C_plus/279*_PerfectSquares.cpp deleted file mode 100644 index c0bad5b..0000000 --- a/C_plus/279*_PerfectSquares.cpp +++ /dev/null @@ -1,72 +0,0 @@ -class Solution -{ -public: - int is_square(int n) - { - int sqrt_n = (int)(sqrt(n)); - return (sqrt_n * sqrt_n == n); - } - - int numSquares(int n) - { - - // option 1 math - // Legendre's three-square theorem,任一正整數皆可用 4 個整數的平方和表示。 - // 2 = {1,1,0,0} 的整數平方和。 - // 也可以說 除了 0 返回結果可能 1,2,3,4個的其中一個,也就是說本題答案介於 [1,4] 區間 - // 任何由四個平方和數字組成的數字,皆可表示成 4^k*(8*m + 7). - // 2 = {1,1} - // 8 = {2,2} - - // if(is_square(n)) - // { - // return 1; - // } - // while (n%4 == 0 ) // ((n & 3) == 0) - // { - // n >>= 2; - // } - // if( n%8 == 7) // ((n & 7) == 7) - // { - // return 4; - // } - - // for (int i = 0; i * i <= n; ++i) { - // if (is_square(n - i*i)) - // { - // return 2; - // } - // } - // return 3; - - // dp - // dp[i] 表示 正整數 i 能由多少個完全平方數組成 - // - // 0 1 2 3 4 5 6 7 8 9 10 11 12 - // + + + + + + + + + + + + + - // 0 - //i=0 0 1 + + 1 + + + + 1 + + + - //i=1 0 1 2 + 1 2 + + + 1 2 + + - //i=2 0 1 2 3 1 2 3 + + 1 2 3 + - //i=3 0 1 2 3 1 2 3 4 + 1 2 3 4 - //i=4 0 1 2 3 1 2 3 4 2 1 2 3 4 - //i=5 0 1 2 3 1 2 3 4 2 1 2 3 4 - //i=6 0 1 2 3 1 2 3 4 2 1 2 3 4 - //i=7 0 1 2 3 1 2 3 4 2 1 2 3 4 - //i=8 0 1 2 3 1 2 3 4 2 1 2 3 4 - //i=9 0 1 2 3 1 2 3 4 2 1 2 3 4 - //i=10 0 1 2 3 1 2 3 4 2 1 2 3 4 - - vector dp(n + 1, INT_MAX); - dp[0] = 0; - for (int i = 0; i <= n; ++i) - { - for (int j = 1; i + j * j <= n; ++j) - { - dp[i + j * j] = min(dp[i + j * j], dp[i] + 1); - } - } - - return dp[n]; - } -}; \ No newline at end of file diff --git a/C_plus/282_ExpressionAddOperators.cpp b/C_plus/282_ExpressionAddOperators.cpp deleted file mode 100644 index ea49c9a..0000000 --- a/C_plus/282_ExpressionAddOperators.cpp +++ /dev/null @@ -1,38 +0,0 @@ -class Solution -{ -public: - void traverse(string num, int target, long diff, long curNum, string out, vector &ret) - { - - if (num.size() == 0 && curNum == target) - { - ret.push_back(out); - return; - } - - for (int i = 1; i <= num.size(); ++i) - { - string cur = num.substr(0, i); - if (cur.size() > 1 && cur[0] == '0') - return; - - string next = num.substr(i); - if (out.size() > 0) - { - traverse(next, target, stoll(cur), curNum + stoll(cur), out + "+" + cur, ret); - traverse(next, target, -stoll(cur), curNum - stoll(cur), out + "-" + cur, ret); - traverse(next, target, diff * stoll(cur), (curNum - diff) + diff * stoll(cur), out + "*" + cur, ret); - } - else - { - traverse(next, target, stoll(cur), stoll(cur), cur, ret); - } - } - } - vector addOperators(string num, int target) - { - vector ret; - traverse(num, target, 0, 0, "", ret); - return ret; - } -}; \ No newline at end of file diff --git a/C_plus/283_MoveZeros.cpp b/C_plus/283_MoveZeros.cpp deleted file mode 100644 index e004675..0000000 --- a/C_plus/283_MoveZeros.cpp +++ /dev/null @@ -1,40 +0,0 @@ -class Solution -{ -public: - int removeElement(vector &nums, int val) - { - - int slow = 0, fast = 0; - while (fast < nums.size()) - { - - if (nums[fast] != val) - { - nums[slow] = nums[fast]; - slow++; - } - fast++; - } - return slow; - } - - void moveZeroes(vector &nums) - { - - // option 1 two pointer - // int n= nums.size(), slow=0; - // for(int i =0;i &nums) - { - // O(nlogn) time and O(10) space - sort(nums.begin(), nums.end()); - for(int i=1;is; - // for(int n:nums) { - // if(s.find(n)!=s.end()) return n; - // s.insert(n); - // } - // return -1; - - // option 2 O(1) space - // slow fast pointer - int slow = 0, fast = 0, t = 0; - // detect cycle exists - while (1) - { - slow = nums[slow]; - fast = nums[nums[fast]]; - if (slow == fast) - break; - } - // find begining of cycle - while (1) - { - slow = nums[slow]; - t = nums[t]; - if (t == slow) - break; - } - return slow; - - // option 3 - // bit-wise hard - } -}; \ No newline at end of file diff --git a/C_plus/289_GameofLife.cpp b/C_plus/289_GameofLife.cpp deleted file mode 100644 index 9704091..0000000 --- a/C_plus/289_GameofLife.cpp +++ /dev/null @@ -1,98 +0,0 @@ -class Solution -{ -public: - void gameOfLife(vector > &board) - { - - // 在八相鄰 鄰居 - - // 任何活著的區域1 - // 任何活著的區域1,少於兩個鄰居活著,代表人口不足,下個階段會死亡0,像示圖座標 (0,1) (2,0) - // 任何活著的區域1,超過三個鄰居活著,人口過剩,下個階段會死亡0,像示圖座標 - // 任何活著的區域1,有兩或三個鄰居活著,持續觀察 next generation下個階段也會活著1維持,像示圖座標(1,2) (2,1) (2,2) - // 兩或三個鄰居活著 代表6或5個死亡 - // - // 任何死亡的區域0 - // 任何死亡的區域0,有著剛好三個活著的鄰居,會被生殖 reproduction,像示圖座標(1,0) (3,1) -> 1 - // (0,0) (0,2) (1,1) (3,0) (3,2) -> 0 - - // option 1 dp - // int m= board.size(), n= board[0].size(); - // vector> next_state(board.begin(), board.end()); - // vector> action = {{-1,-1},{-1,0},{-1,1}, - // {0,-1},{0,1}, - // {1,-1},{1,0},{1,1}}; - // for(int i=0;i > action = {{-1, -1}, {-1, 0}, {-1, 1}, {0, -1}, {0, 1}, {1, -1}, {1, 0}, {1, 1}}; - for (int i = 0; i < m; ++i) - { - for (int j = 0; j < n; ++j) - { - int num_live = 0; - for (pair a : action) - { - int x = i + a.first, y = j + a.second; - if (x >= 0 && x < m && y >= 0 && y < n && (board[x][y] == 1 || board[x][y] == 2)) - { - ++num_live; - } - } - - if (board[i][j] && (num_live < 2 || num_live > 3)) - board[i][j] = 2; - else if (!board[i][j] && num_live == 3) - board[i][j] = 3; - } - } - - for (int i = 0; i < m; ++i) - { - for (int j = 0; j < n; j++) - { - board[i][j] = board[i][j] % 2; - } - } - } - - void neighborSearch(vector > &board, vector > &dp, int i, int j, vector > &action) - { - int num_die = 0, num_live = 0; - int m = board.size(), n = board[0].size(); - - for (pair a : action) - { - int neighbor_x = i + a.first, neighbor_y = j + a.second; - if (neighbor_x < 0 || neighbor_x > m - 1 || neighbor_y < 0 || neighbor_y > n - 1) - continue; - num_die += (board[neighbor_x][neighbor_y] == 0) ? 1 : 0; - num_live += (board[neighbor_x][neighbor_y] == 1) ? 1 : 0; - } - if (board[i][j] == 0) - { - if (num_live == 3) - dp[i][j] = 1; - } - else if (board[i][j] == 1) - { - if (num_live < 2) - dp[i][j] = 0; - else if (num_live > 3) - dp[i][j] = 0; - // else if(num_live==2 || num_die==3) continue; // dp[i][j] = 1; - } - } -}; \ No newline at end of file diff --git a/C_plus/28_ImplementstrStr().cpp b/C_plus/28_ImplementstrStr().cpp deleted file mode 100644 index 5b21b8a..0000000 --- a/C_plus/28_ImplementstrStr().cpp +++ /dev/null @@ -1,66 +0,0 @@ -class Solution { -public: - int strStr(string haystack, string needle) { - - - - // option 1 brute force O(MN) time and O(1) space - -// if(haystack.size()==0 && needle.size()==0 ) return 0; -// if(needle.size()>haystack.size()) return -1; - -// int ret = -1; -// for(int i=0;i<=haystack.size()-needle.size();++i){ - -// int tmp = 0; -// for(int j=0;j haystack.size()) return -1; - - - int n =haystack.size(), m = needle.size(); - - vector shift(128, m + 1); - // 位移表 - // 模式串P中每个字母出现的最后的下标 - // 所对应的主串参与匹配的最末位字符的下一位字符移动到该位,所需要的移动位数 - for(int i = 0; i < m; i++) { - shift[needle[i]] = m - i; - } - - // 模式串開始位置 - int s =0; - // 模式串已經匹配到的位置 - int j; - while(s <= n-m){ - j = 0; - while(haystack[s +j] == needle[j]){ - j++; - if(j>=m){ - // 匹配成功 - return s; - } - } - // 匹配不成功 - s += shift[haystack[s + m]]; - - } - return -1; - - - } -}; \ No newline at end of file diff --git a/C_plus/29*_DivideTwoIntegers.cpp b/C_plus/29*_DivideTwoIntegers.cpp deleted file mode 100644 index c5d0977..0000000 --- a/C_plus/29*_DivideTwoIntegers.cpp +++ /dev/null @@ -1,28 +0,0 @@ -class Solution -{ -public: - int divide(int dividend, int divisor) - { - - if (dividend == INT_MIN && divisor == -1) - return INT_MAX; - long m = labs(dividend), n = labs(divisor), ret = 0; - int sign = ((dividend < 0) ^ (divisor < 0)) ? -1 : 1; - if (n == 1) - return sign == 1 ? m : -m; - - while (m >= n) - { - long t = n, p = 1; - while (m >= (t << 1)) - { - t <<= 1; - p <<= 1; - } - cout << p << " " << t << endl; - ret += p; - m -= t; - } - return sign == 1 ? ret : -ret; - } -}; \ No newline at end of file diff --git a/C_plus/290_WordPattern.cpp b/C_plus/290_WordPattern.cpp deleted file mode 100644 index 114262a..0000000 --- a/C_plus/290_WordPattern.cpp +++ /dev/null @@ -1,48 +0,0 @@ -class Solution -{ -public: - bool wordPattern(string pattern, string s) - { - - vector words; - int j = 0; - s += ' '; - while (s[j] == ' ') - j++; - for (int i = j; i < s.size(); ++i) - { - if (s[i] == ' ') - { - words.push_back(s.substr(j, i - j)); - while (i < s.size() && s[i] == ' ') - i++; - j = i; - } - } - // for(string w:words) cout< mp; - unordered_map mpi; - - for (int i = 0; i < pattern.size(); ++i) - { - if (mp.count(pattern[i]) || mpi.count(words[i])) - { - if (mpi[words[i]] != pattern[i]) - return false; - if (mp[pattern[i]] != words[i]) - return false; - } - else - { - - mp[pattern[i]] = words[i]; - mpi[words[i]] = pattern[i]; - } - } - return true; - } -}; \ No newline at end of file diff --git a/C_plus/292*_NimGame.cpp b/C_plus/292*_NimGame.cpp deleted file mode 100644 index 7fb67c6..0000000 --- a/C_plus/292*_NimGame.cpp +++ /dev/null @@ -1,10 +0,0 @@ -class Solution { -public: - bool canWinNim(int n) { - // 假設雙方一樣聰明,並且我方先起手 - // n = 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 - // result= t t t f t t t f t t t f t t t - - return n%4 !=0; - } -}; \ No newline at end of file diff --git a/C_plus/295*_FindMedianfromDataStream.cpp b/C_plus/295*_FindMedianfromDataStream.cpp deleted file mode 100644 index 35fbf79..0000000 --- a/C_plus/295*_FindMedianfromDataStream.cpp +++ /dev/null @@ -1,53 +0,0 @@ -class MedianFinder -{ -private: - // - priority_queue up; // 不變,因為C++ 預設小的優先取出 - priority_queue, greater > down; - -public: - /** initialize your data structure here. */ - MedianFinder() - { - // 中位數位於金字塔的中間,將金字塔從中橫切一刀。可分為上下兩部分 - // 大於中位數的金字塔上部分用min heap up儲存 - // 小於中位數的金字塔下部分用max heap down 儲存 - } - - void addNum(int num) - { // O(nlogn) time - - if (up.size() >= down.size()) - { - up.push(num); - down.push(up.top()); - up.pop(); - } - else - { - down.push(num); - up.push(down.top()); - down.pop(); - } - } - - double findMedian() - { // O(1) time - - // option 1 - if (up.size() > down.size()) - return up.top(); - else if (up.size() < down.size()) - return down.top(); - return (up.top() + down.top()) / 2.0; - - //option 2 相反數 - } -}; - -/** - * Your MedianFinder object will be instantiated and called as such: - * MedianFinder* obj = new MedianFinder(); - * obj->addNum(num); - * double param_2 = obj->findMedian(); - */ \ No newline at end of file diff --git a/C_plus/2_AddTwoNumbers.cpp b/C_plus/2_AddTwoNumbers.cpp deleted file mode 100644 index 46ba3af..0000000 --- a/C_plus/2_AddTwoNumbers.cpp +++ /dev/null @@ -1,43 +0,0 @@ -/** - * Definition for singly-linked list. - * struct ListNode { - * int val; - * ListNode *next; - * ListNode() : val(0), next(nullptr) {} - * ListNode(int x) : val(x), next(nullptr) {} - * ListNode(int x, ListNode *next) : val(x), next(next) {} - * }; - */ -class Solution -{ -public: - ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) - { - ListNode *res = new ListNode(); - ListNode *ret = res; - int carry = 0; - while (l1 || l2) - { - int sum = carry; - if (l1) - { - sum += l1->val; - l1 = l1->next; - } - if (l2) - { - sum += l2->val; - l2 = l2->next; - } - ListNode *cur = new ListNode(sum % 10); - carry = sum / 10; - res->next = cur; - res = res->next; - } - if (carry) - { - res->next = new ListNode(carry); - } - return ret->next; - } -}; \ No newline at end of file diff --git a/C_plus/300*_LongestIncreasingSubsequence.cpp b/C_plus/300*_LongestIncreasingSubsequence.cpp deleted file mode 100644 index 6e9ae10..0000000 --- a/C_plus/300*_LongestIncreasingSubsequence.cpp +++ /dev/null @@ -1,59 +0,0 @@ -class Solution -{ -public: - int lengthOfLIS(vector &nums) - { - // option 1 use dp 到目前為止的最長子序列長度 - // O(n^2) dp - // 10 9 2 5 3 7 101 18 - // 1 1 1 1 1 1 1 1 - // i=1 1 1 - // i=2 1 1 1 - // i=3 1 1 1 2 - // i=4 1 1 1 2 2 - // i=5 1 1 1 2 2 3 - // i=6 1 1 1 2 2 3 4 - // i=7 1 1 1 2 2 3 4 4 - - // int n = nums.size(), ret = 0; - // vector dp(n, 1); - // for(int i=0;inums[j]) dp[i] = max(dp[j]+1, dp[i]); - // } - // ret = max(ret, dp[i]); - // // 每次更新dp[i] 都來更新一下最大值 - // } - - // return ret; - - // option 2 Binary search O(nlogn) - - int n = nums.size(); - vector top(n, 0); // 牌堆初始化0 - int piles = 0; - for (int i = 0; i < n; ++i) - { - - int poker = nums[i]; // 要處理的撲克牌 - - int left = 0, right = piles; - while (left < right) - { - int mid = left + (right - left) / 2; - if (top[mid] > poker) - right = mid; - else if (top[mid] < poker) - left = mid + 1; - else - right = mid; - } - //沒找到合適的牌堆,新建一堆 - if (left == piles) - piles++; - top[left] = poker; - } - - return piles; - } -}; diff --git a/C_plus/309*_BestTimetoBuyandSellStockwithCooldown.cpp b/C_plus/309*_BestTimetoBuyandSellStockwithCooldown.cpp deleted file mode 100644 index b4e53eb..0000000 --- a/C_plus/309*_BestTimetoBuyandSellStockwithCooldown.cpp +++ /dev/null @@ -1,52 +0,0 @@ -class Solution -{ -public: - int maxProfit(vector &prices) - { - // option 1 use dp - // https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/discuss/75928/Share-my-DP-solution-(By-State-Machine-Thinking) - // dp[i][0] = max(dp[i-1][0], dp[i-1][1] + prices[i]) - // dp[i][1] = max(dp[i-1][1], dp[i-2][0] - prices[i]) - // 解释:第 i 天选择 buy 的时候,要从 i-2 的状态转移,而不是 i-1 。 - // 每次 sell 之后要等一天才能继续交易buy買 - // 1 2 3 0 2 - // sell(0) hold(1) - // dp[i][0] = max( dp[i-1][0], dp[i-1][1] + prices[i]); - // dp[i][1] = max( dp[i-1][1], dp[i-2][0] - prices[i]); - - //1 0 -1 - //2 1 -1 - //3 2 -1 - //0 2 1 - //2 3 1 - // int n = prices.size(); - // if(n==1) return 0; - // vector> dp(n ,vector(2,0)); - // dp[0][1] = -prices[0]; - // dp[1][0] = max(dp[0][0], dp[0][1]+ prices[1]); - // dp[1][1] = max(dp[0][1], -prices[1]); - // for(int i=2;i &nums) - { - // https://en.wikipedia.org/wiki/Permutation#Generation_in_lexicographic_order - // 給定陣列如果是 降序,說明是全排列的最後一種情況,下一個排序則是初始排序 - // 1 2 7 4 3 1 - // 1 3 1 2 4 7 下一排列 - // step 1. 從右往左看,數字逐漸變大,直到2時才變小, - // step 2. 然後在從右往前找第一個比 2 大的數字,是3 - // step 3. 將 2 3 交換, - // step 4. 把3後面的數字反轉,讓其保持升序 - - int n = nums.size(); - int k; - // step 1. - // 找 最大索引 滿足 nums[k] < nums[k + 1] - for (k = n - 2; k > -1; k--) - { - if (nums[k] < nums[k + 1]) - break; - } - // k 小於 0 代表 給定陣列如果是 降序,說明是全排列的最後一種情況,下一個排序則是初始排序 - if (k < 0) - reverse(nums.begin(), nums.end()); - else - { - // step 2. 然後在從右往前找第一個比 2 大的數字,是3 - int l; - for (l = n - 1; l > k; l--) - { - if (nums[l] > nums[k]) - break; - } - cout << l; - - // step 3. - swap(nums[k], nums[l]); - // step 4. - reverse(nums.begin() + k + 1, nums.end()); - } - } -}; \ No newline at end of file diff --git a/C_plus/312*_BurstBalloons.cpp b/C_plus/312*_BurstBalloons.cpp deleted file mode 100644 index 0110255..0000000 --- a/C_plus/312*_BurstBalloons.cpp +++ /dev/null @@ -1,33 +0,0 @@ -class Solution { -public: - int maxCoins(vector& nums) { - int n = nums.size(); - vector> dp(n+2, vector(n+2,0)); - vector points(n+2, 0); - points[0] = 1, points[n+1] = 1; - for(int i=1;i<=n;++i) points[i] = nums[i-1]; - - // dp[i][j] = dp[i][k] + dp[k][j] + nums[i]*nums[k]*nums[j]; - // 3 1 5 8 - // 0 0 - // 0 0 - // 3 - // 1 - // 5 - // 8 - - // i 從下往上 - for(int i=n; i>=0 ;i--){ - // j 從左往右 - for(int j = i+1;j< n+2 ; ++j){ - // 最後戳破 的氣球是哪一顆 - for(int k = i+1; k countSmaller(vector &nums) - { - // option 1 O(n) brute force time out - // int n =nums.size(); - // vector vec(n,0); - - // for(int i=0;i vec; - // vector ret(n,0); - // for(int i=n-1;i>-1;i--){ - // int l = 0, r=vec.size(); - // while(l sta; - vector instack(256,false); - vector count(256); - for(char c:s) count[c]++; - - for(char c:s){ - - count[c]--; - - if( instack[c]) continue; - - // monotonic stack - while(!sta.empty() && sta.top() > c){ - // 須先判斷此字元在字串中是否唯一,否則pop掉就完了 - if(count[sta.top()]==0) break; - instack[sta.top()] = false; - sta.pop(); - } - - - sta.push(c); - instack[c] = true; - } - - string ret; - while(!sta.empty()){ - ret.insert(ret.begin(), sta.top()); - sta.pop(); - - } - cout< &words) - { - // option 1 O(n^3) maybe time out - int n = words.size(); - vector > wordSet(n); - for (int i = 0; i < n; ++i) - { - for (char c : words[i]) - wordSet[i].insert(c); - } - int ret = 0; - for (int i = 0; i < n; ++i) - { - for (int j = i + 1; j < n; ++j) - { - bool f = true; - for (char c : words[j]) - { - if (wordSet[i].count(c)) - { - f = false; - break; - } - } - if (f) - { - // cout< sta; - // int start = 0; - // for(int i=0;i dp(n+1,0); - // for(int i=1;i<=n ; ++i){ - // int j = i - 2 -dp[i-1]; - // if(s[i-1] == '(' || j<0 || s[j] == ')') dp[i]= 0 ; - // else{ - // dp[i] = dp[i-1] + 2 + dp[j]; - // maxLen = max(maxLen, dp[i]); - // } - // } - // return maxLen; - - // option 3 - // two pointer - int n = s.size(); - int l = 0, r = 0; - - int res = 0; - for (int i = 0; i < n; ++i) - { - - if (s[i] == '(') - l++; - else - r++; - if (l == r) - res = max(res, 2 * r); - else if (r > l) - l = r = 0; - } - l = r = 0; - for (int i = n - 1; i >= 0; --i) - { - if (s[i] == '(') - l++; - else - r++; - if (l == r) - res = max(res, 2 * l); - else if (l > r) - l = r = 0; - } - return res; - } -}; \ No newline at end of file diff --git a/C_plus/322*_CoinChange.cpp b/C_plus/322*_CoinChange.cpp deleted file mode 100644 index a27464b..0000000 --- a/C_plus/322*_CoinChange.cpp +++ /dev/null @@ -1,92 +0,0 @@ -class Solution -{ -public: - int change(vector &coins, int amount) - { - // base case - if (amount == 0) - return 0; - if (amount < 0) - return -1; - - int ret = INT_MAX; - for (int coin : coins) - { - int subproblem = change(coins, amount - coin); - if (subproblem == -1) - continue; - ret = min(ret, 1 + subproblem); - } - return ret == INT_MAX ? -1 : ret; - } - int change(vector &coins, int amount, unordered_map &memo) - { - // 查看備忘錄是否已存在 - if (memo.count(amount)) - return memo[amount]; - - // base case - if (amount == 0) - return 0; - if (amount < 0) - return -1; - - int ret = INT_MAX; - - for (int coin : coins) - { - int subproblem = change(coins, amount - coin, memo); - if (subproblem == -1) - continue; - ret = min(ret, 1 + subproblem); - } - // 放進備忘錄 - memo[amount] = ret == INT_MAX ? -1 : ret; - return memo[amount]; - } - int coinChange(vector &coins, int amount) - { - - // option 1 brute force recursive - // Time Limit Exceeded - - // 想求amount = 11 時最少硬幣數,必須先知道amount = 10時最少硬幣數,以此類推。 - // return change(coins, amount); - - // option 2 memo pattern - unordered_map memo; - return change(coins, amount, memo); - - // option 3 dp - // - // 0 1 2 3 4 5 6 7 8 9 10 11 - // 11 11 11 11 11 11 11 11 11 11 11 11 - // 1 0 1 2 3 4 5 6 7 8 9 10 11 - // 2 0 1 1 - // 5 0 - // if(j>= coins[i] ) dp[i][j] = min(dp[i-1][j], dp[i][j-coins[i]] + 1); - // else dp[i][j] = dp[i-1][j]; - // int n = coins.size(); - // vector> dp(n+1, vector(amount+1,amount+1)); - // for(int i=0;i<=n ; ++i) dp[i][0] = 0; //initialize - // for(int i=1;i<=n ;++i){ - // for(int j=1;j<=amount ;++j){ - // if(j >= coins[i-1]) dp[i][j] = min(dp[i-1][j], dp[i][j-coins[i-1]] + 1); - // else dp[i][j] = dp[i-1][j]; - // } - // } - // return dp[n][amount] == amount+1?-1:dp[n][amount]; - - // option 4 壓縮 dp - - // int n = coins.size(); - // vector dp(amount+1,amount+1); - // dp[0] = 0; //initialize - // for(int i=0;i= coins[i]) dp[j] = min(dp[j], dp[j-coins[i]] +1 ); - // } - // } - // return dp[amount] == amount+1?-1:dp[amount]; - } -}; \ No newline at end of file diff --git a/C_plus/324*_WiggleSortII.cpp b/C_plus/324*_WiggleSortII.cpp deleted file mode 100644 index f72e412..0000000 --- a/C_plus/324*_WiggleSortII.cpp +++ /dev/null @@ -1,29 +0,0 @@ -class Solution -{ -public: - void wiggleSort(vector &nums) - { - // option 1 O(NlogN) time and O(N) space - // 1. copy a vector 2. sorted this vector - // 3. 從中間切兩半,兩個索引分別指向左半部(小數字)及右半部(大數字部分) - // 4. 利用索引奇偶數 去 判斷拿 左半部還是右半部 - - vector vec = nums; - sort(vec.begin(), vec.end()); - int n = nums.size(); - int small = (n - 1) / 2, large = n - 1; - for (int i = 0; i < n; ++i) - { - if (i % 2 == 0) - { - // pick small - nums[i] = vec[s--]; - } - else - { - // pick large - nums[i] = vec[l--]; - } - } - } -}; \ No newline at end of file diff --git a/C_plus/326_PowerOfThree.cpp b/C_plus/326_PowerOfThree.cpp deleted file mode 100644 index b0e9e56..0000000 --- a/C_plus/326_PowerOfThree.cpp +++ /dev/null @@ -1,21 +0,0 @@ -class Solution -{ -public: - bool isPowerOfThree(int n) - { - // option 1 - // loop - // if(n<1) return false; - // while(n%3==0) n/=3; - // return n==1; - - // option 2 - // without loops/recursion - // tricky 3^19=1162261467 ,任何只要是3的指數一定能被他整除。 - // return (n>0 && 1162261467%n==0); - - // option 3 - // 換底公式 + a-int(a)==0 - return (n > 0 && (int(log10(n) / log10(3)) - (log10(n) / log10(3)) == 0)); - } -}; \ No newline at end of file diff --git a/C_plus/328_OddEvenLinkedList.cpp b/C_plus/328_OddEvenLinkedList.cpp deleted file mode 100644 index 3a162ab..0000000 --- a/C_plus/328_OddEvenLinkedList.cpp +++ /dev/null @@ -1,46 +0,0 @@ -/** - * Definition for singly-linked list. - * struct ListNode { - * int val; - * ListNode *next; - * ListNode() : val(0), next(nullptr) {} - * ListNode(int x) : val(x), next(nullptr) {} - * ListNode(int x, ListNode *next) : val(x), next(next) {} - * }; - */ -class Solution -{ -public: - ListNode *oddEvenList(ListNode *head) - { - // option 1 - // two pointer , pointer odd, even - // if(!head || !head->next) return head; - // ListNode* odd =head, *even = head->next; - // ListNode *p = even; - // while(odd->next && even->next){ - // odd->next = even->next; - // even->next = even->next->next; - // odd=odd->next; - // even=even->next; - // } - // odd->next = p; - // return head; - - // option 2 - if (!head || !head->next) - return head; - ListNode *pre = head, *cur = head->next; - while (cur && cur->next) - { - ListNode *tmp = pre->next; - pre->next = cur->next; - cur->next = cur->next->next; - pre->next->next = tmp; - pre = pre->next; - cur = cur->next; - } - - return head; - } -}; \ No newline at end of file diff --git a/C_plus/33*_SearchInRotatedSortedArray.cpp b/C_plus/33*_SearchInRotatedSortedArray.cpp deleted file mode 100644 index 9d0881a..0000000 --- a/C_plus/33*_SearchInRotatedSortedArray.cpp +++ /dev/null @@ -1,33 +0,0 @@ -class Solution -{ -public: - int search(vector &nums, int target) - { - // binary search O(logn) time - int n = nums.size(); - int l = 0, r = n - 1; - while (l <= r) - { - int mid = l + (r - l) / 2; - if (nums[mid] == target) - return mid; - else if (nums[mid] < nums[r]) - { - // 右邊是遞增數列 - if (target > nums[mid] && target <= nums[r]) - l = mid + 1; - else - r = mid - 1; - } - else - { - // 左邊是遞增數列,加等好是因為mid==l時 - if (target >= nums[l] && nums[mid] >= target) - r = mid - 1; - else - l = mid + 1; - } - } - return -1; - } -}; \ No newline at end of file diff --git a/C_plus/331*_VerifyPreorderSerializationofaBinaryTree.cpp b/C_plus/331*_VerifyPreorderSerializationofaBinaryTree.cpp deleted file mode 100644 index e076a78..0000000 --- a/C_plus/331*_VerifyPreorderSerializationofaBinaryTree.cpp +++ /dev/null @@ -1,31 +0,0 @@ -class Solution -{ -public: - bool isValidSerialization(string preorder) - { - - // 數字個數一比 # 少一個 - // 最後一個一定是 # - // 扣掉最後一個# 數字個數和# 個數應該相同 - - istringstream in(preorder); - vector v; - string t; - int cnt = 0; - while (getline(in, t, ',')) - v.push_back(t); - for (int i = 0; i < v.size() - 1; ++i) - { - if (v[i] == "#") - { - if (cnt == 0) - return false; - cnt--; - } - else - cnt++; - } - - return cnt == 0 && v.back() == "#"; - } -}; \ No newline at end of file diff --git a/C_plus/334*_IncreasingTripletSubsequence.cpp b/C_plus/334*_IncreasingTripletSubsequence.cpp deleted file mode 100644 index 34f8781..0000000 --- a/C_plus/334*_IncreasingTripletSubsequence.cpp +++ /dev/null @@ -1,43 +0,0 @@ -class Solution -{ -public: - bool increasingTriplet(vector &nums) - { - - // O(n) time and O(n) space - // 用兩組陣列維護 最大及最小值。 - // if(nums.size()<3) return false; - // int n = nums.size(); - // vector mn(n, INT_MAX), mx(n, INT_MIN); - - // for(int i=1;i-1;i--){ - // mx[i] = max(nums[i+1], mx[i+1]); - // } - // for(int i=1;i m1 && nums[i] <= m2) - m2 = nums[i]; - else - return true; - } - - return false; - } -}; \ No newline at end of file diff --git a/C_plus/337*_HouseRobberIII.cpp b/C_plus/337*_HouseRobberIII.cpp deleted file mode 100644 index 7ae4027..0000000 --- a/C_plus/337*_HouseRobberIII.cpp +++ /dev/null @@ -1,34 +0,0 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution { -private: - unordered_map memo; -public: - int rob(TreeNode* root) { - // 事關三層 - if(root==nullptr) return 0; - - if(memo[root]) return memo[root]; - - // 搶 - int do_it = root->val; - if(root->left!=nullptr) do_it += rob(root->left->left) +rob(root->left->right); - if(root->right !=nullptr) do_it += rob(root->right->left) + rob(root->right->right); - // 不搶 - int not_do = rob(root->left) + rob(root->right); - int res = max(not_do, do_it); - memo[root] = res; - return res; - - - } -}; \ No newline at end of file diff --git a/C_plus/338_CountingBit.cpp b/C_plus/338_CountingBit.cpp deleted file mode 100644 index b8278b9..0000000 --- a/C_plus/338_CountingBit.cpp +++ /dev/null @@ -1,80 +0,0 @@ -class Solution -{ -public: - int count(int d) - { - int ret = 0; - while (d) - { - ret++; - d = d & (d - 1); - } - return ret; - } - - vector countBits(int n) - { - // option 1 baseline O(nlogn) - // vector ret; - // int tmp =0 ; - // for(int i =0;i<=n;++i){ - // tmp = i; - // int count = 0; - // while(tmp){ - // count += (tmp&1); - // tmp >>=1; - // } - // ret.push_back(count); - - // } - // return ret; - - // option 1.1 - if (n == 0) - return {0}; - vector v = {0, 1}; - for (int i = 2; i <= n; ++i) - { - v.emplace_back(count(i)); - } - return v; - - // option 2 inspiration from hint 2 - // O(n) - // if (n == 0) return {0}; - // vector ret = {0,1}; - // int k =2,i=2; - // while(i<=n){ - // for(i=pow(2,k-1); in) break; - // int t = (pow(2,k)-pow(2,k-1))/2; - // if(i ret = {0}; - // for(int i =1;i<=n;++i){ - // if(i%2==0) ret.push_back(ret[i/2]); - // else ret.push_back(ret[i/2]+1); - // } - - // return ret; - - // option 4 - // O(n) - // 8 有幾個一 == ret[8&7]+1 == ret[1000&0111]+1 = ret[0]+1 - // 13 有幾個一 == ret[13&12]+1 == ret[1101&1100]+1 = ret[12] +1 - vector ret(n + 1, 0); - for (int i = 1; i <= n; ++i) - { - ret[i] = ret[i & (i - 1)] + 1; - } - return ret; - } -}; \ No newline at end of file diff --git a/C_plus/34.FindFirstandLastPositionofElementinSortedArray.cpp b/C_plus/34.FindFirstandLastPositionofElementinSortedArray.cpp deleted file mode 100644 index b62c36c..0000000 --- a/C_plus/34.FindFirstandLastPositionofElementinSortedArray.cpp +++ /dev/null @@ -1,51 +0,0 @@ -class Solution -{ -public: - vector searchRange(vector &nums, int target) - { - - // binary search - // 尋找左邊界 框架 - // [1,2,3,4,7,8,10] , target = 6 - // left = 4 ,代表該數組小於target = 6的有4個 - // if(nums.empty()) return {-1,-1}; - // if(nums.back() < target || target < nums[0]) return {-1,-1}; - - // int left =0, right = nums.size()-1; - // while(left<=right){ - // int mid = left + (right-left)/2; - // if(nums[mid] == target) right = mid-1; - // else if(nums[mid] > target) right = mid-1; - // else if(nums[mid] < target) left = mid +1; - // } - // cout< ret = {left}; - // // left < nums.size()-1 防止nums[left+1] 溢位 - // while(left < nums.size()-1 && nums[left] == nums[left+1]) left++; - // ret.push_back(left); - // return ret; - - // version 2 - if (nums.empty()) - return {-1, -1}; - int left = 0, right = nums.size(); - while (left < right) - { - int mid = left + (right - left) / 2; - if (nums[mid] == target) - right = mid; - else if (nums[mid] > target) - right = mid; - else if (nums[mid] < target) - left = mid + 1; - } - if (left > nums.size() - 1 || nums[left] != target) - return {-1, -1}; - vector ret = {left}; - while (left < nums.size() - 1 && nums[left] == nums[left + 1]) - left++; - ret.push_back(left); - return ret; - } -}; \ No newline at end of file diff --git a/C_plus/342_PowerofFour.cpp b/C_plus/342_PowerofFour.cpp deleted file mode 100644 index be79485..0000000 --- a/C_plus/342_PowerofFour.cpp +++ /dev/null @@ -1,22 +0,0 @@ -class Solution -{ -public: - bool isPowerOfFour(int n) - { - - // option 1 - // if(n<1) return false; - // while(n%4==0){ - // n /=4; - // } - // return n==1; - - // option 2 without loops/recursion - // (0x55555555) <==> 1010101010101010101010101010101 - if (n < 1) - return false; - if ((n & (n - 1)) != 0) - return false; - return (n & 0x55555555) == n; - } -}; \ No newline at end of file diff --git a/C_plus/343*_IntegerBreak.cpp b/C_plus/343*_IntegerBreak.cpp deleted file mode 100644 index 3bfd186..0000000 --- a/C_plus/343*_IntegerBreak.cpp +++ /dev/null @@ -1,25 +0,0 @@ -class Solution { -public: - int integerBreak(int n) { - // # n =2, => 1+1 , 1*1 =1 - // # n= 3 => 2+1 , 2*1 = 2 - // # n =4 => 2+2 , 2*2 = 4 - // # n = 5 => 3+2 , 2*3 =6 - // # n = 6 => 3+3 , 3*3 = 9 - // # n = 7 => 3+4 , 3*4 = 12 - // # n = 8 => 3+3+2, 3*3*2 = 18 - // # n = 9 => 3++3+2 , 3*3*3= 27 - // # n = 10 => 4+3+3 => 4*3*3 = 36 - // # 先將3拆分出來,拆到只剩2或4 - // # 0 1 2 3 4 5 6 7 8 9 10 - // # 1 1 1 1 1 1 1 1 1 1 1 - // # 1 1 1 2 4 6 9 12 18 27 36 - vector dp(n+1, 1); - for(int i=3;i &s) - { - // option 1 stack support not in-place - // stack sta; - // vector ret; - // for(char c:s) sta.push(c); - - // while(!sta.empty()){ - // ret.push_back(sta.top()); - // sta.pop(); - // } - // s = ret; - - // option 1.1 stack support in-place - // stack sta; - // vector ret; - // for(char c:s) sta.push(c); - // int i=0; - // while(!sta.empty()){ - // s[i++] = sta.top(); - // sta.pop(); - // } - - // option 2 two point and swap - int l = 0, r = s.size() - 1; - while (l < r) - { - swap(s[l++], s[r--]); - } - } -}; \ No newline at end of file diff --git a/C_plus/347_TopKFrequentElements.cpp b/C_plus/347_TopKFrequentElements.cpp deleted file mode 100644 index f7d35c9..0000000 --- a/C_plus/347_TopKFrequentElements.cpp +++ /dev/null @@ -1,25 +0,0 @@ -class Solution -{ -public: - vector topKFrequent(vector &nums, int k) - { - // option 1 - unordered_map m; - vector ret; - priority_queue > pq; - - for (int i = 0; i < nums.size(); ++i) - m[nums[i]]++; - - for (auto a : m) - pq.push(make_pair(a.second, a.first)); - - while (!pq.empty() && k) - { - ret.emplace_back(pq.top().second); - pq.pop(); - k--; - } - return ret; - } -}; \ No newline at end of file diff --git a/C_plus/349_IntersectionOfTwoArrays.cpp b/C_plus/349_IntersectionOfTwoArrays.cpp deleted file mode 100644 index a809bb1..0000000 --- a/C_plus/349_IntersectionOfTwoArrays.cpp +++ /dev/null @@ -1,76 +0,0 @@ -class Solution -{ -public: - vector intersection(vector &nums1, vector &nums2) - { - // option 1 O(nlogn) time and O(n) space - // set tmp(nums1.begin(), nums1.end()); - // set ret; - // for(int n:nums2) if(tmp.find(n)!=tmp.end()) ret.insert(n); - // return vector (ret.begin(), ret.end()); // convert set to vector - - // option 2 - // two pointer O(nlogn) time and O(1) space - sort(nums1.begin(), nums1.end()); - sort(nums2.begin(), nums2.end()); - vector ret; - int l = 0, r = 0; - while (l < nums1.size() && r < nums2.size()) - { - if (nums1[l] == nums2[r]) - { - if (ret.empty() || ret.back() != nums1[l]) - ret.push_back(nums1[l]); - l++; - r++; - } - else if (nums1[l] < nums2[r]) - l++; - else - r++; - } - return ret; - - // option 3 - // binary search - // O(nlogn) - set ret; - sort(nums1.begin(), nums1.end()); - for (int n : nums2) - { - if (BinarySearch(nums1, n)) - ret.insert(n); - } - - return vector(ret.begin(), ret.end()); - - // option 4 O(n) time and O(1) space - vector ret; - vector his(1000, false); - for (int n : nums1) - his[n] = true; - for (int n : nums2) - { - if (his[n]) - ret.push_back(n); - his[n] = false; - } - return ret; - } - bool BinarySearch(vector &nums, int target) - { - - int l = 0, r = nums.size() - 1; - while (l <= r) - { - int mid = (l + r) / 2; - if (target == nums[mid]) - return true; - else if (nums[mid] < target) - l = mid + 1; - else - r = mid - 1; - } - return false; - } -}; \ No newline at end of file diff --git a/C_plus/350_IntersectionOfTwoArraysII.cpp b/C_plus/350_IntersectionOfTwoArraysII.cpp deleted file mode 100644 index 6eadcf3..0000000 --- a/C_plus/350_IntersectionOfTwoArraysII.cpp +++ /dev/null @@ -1,74 +0,0 @@ -class Solution -{ -public: - vector intersect(vector &nums1, vector &nums2) - { - // option 1 - // O(1000*1000) - - // vector ret1(1001,0); // record frequency - // vector ret2(1001,0); // record frequency - // for(int n:nums1) ret1[n]++; - // for(int n:nums2) ret2[n]++; - - // vector ret; - // for(int i=0;i0 && ret2[i]>0){ - // int freq = min(ret1[i], ret2[i]); - // while(freq){ - // freq--; - // ret.push_back(i); - // } - // } - // } - // return ret; - - // option 2 O(n) time and O(n) space - // make use to map instead of two vector - vector ret; - unordered_map m; - for(int n:nums1) m[n]++; - for(int n:nums2){ - if(m[n]>0){ - ret.push_back(n); - m[n]--; - } - } - return ret; - - // option 2.2 one vector - vector his(1000,0); - vector ret; - for(int n:nums1) his[n]++; - for(int n:nums2){ - if(his[n]>0){ - ret.push_back(n); - his[n]--; - } - } - return ret; - - - - // option 3 - // use two pointer O(n) - sort(nums1.begin(), nums1.end()); - sort(nums2.begin(), nums2.end()); - int l = 0, r = 0; - vector ret; - while (l < nums1.size() && r < nums2.size()) - { - if (nums1[l] == nums2[r]) - { - ret.push_back(nums1[l]); - l++; - r++; - } - else if (nums1[l] > nums2[r]) - r++; - else - l++; - } - return ret; - } -}; \ No newline at end of file diff --git a/C_plus/354*_RussianDollEnvelopes.cpp b/C_plus/354*_RussianDollEnvelopes.cpp deleted file mode 100644 index f510b6e..0000000 --- a/C_plus/354*_RussianDollEnvelopes.cpp +++ /dev/null @@ -1,78 +0,0 @@ -class Solution -{ -public: - static bool compare(vector &a, vector &b) - { - if (a[0] == b[0]) - return a[1] > b[1]; - else - return a[0] < b[0]; // 升序 - } - int maxEnvelopes(vector > &envelopes) - { - // step1. 先對w做升序,如果遇到w相同,用h做降序 - // step2. 基於上述排序,搜集h遞增子序列 - // step3. 針對h做最長遞增子序列 - - int n = envelopes.size(); - //先對w做升序,如果遇到w相同,用h做降序 - sort(envelopes.begin(), envelopes.end(), compare); - - // 基於上述排序,搜集h遞增子序列 - vector ret(n, 0); - for (int i = 0; i < n; ++i) - { - ret[i] = envelopes[i][1]; - } - - // 基於上述排序,搜集h遞增子序列 - return lengthOfLIS(ret); - } - // leetcode - 300. - int lengthOfLIS(vector &nums) - { - // // option 1 use dp 到目前為止的最長子序列長度 - // // O(n^2) dp - // // 10 9 2 5 3 7 101 18 - // // 1 1 1 2 2 3 4 4 dp[i] = max(dp[i], dp[j] +1) - // int n = nums.size(), ret = 0; - // vector dp(n, 1); - // for(int i=0;inums[j]) dp[i] = max(dp[j]+1, dp[i]); - // } - // ret = max(ret, dp[i]); - // // 每次更新dp[i] 都來更新一下最大值 - // } - - // return ret; - - int n = nums.size(); - vector top(n, 0); // 牌堆初始化0 - int piles = 0; - for (int i = 0; i < n; ++i) - { - - int poker = nums[i]; // 要處理的撲克牌 - - int left = 0, right = piles; - while (left < right) - { - int mid = left + (right - left) / 2; - if (top[mid] > poker) - right = mid; - else if (top[mid] < poker) - left = mid + 1; - else - right = mid; - } - //沒找到合適的牌堆,新建一堆 - if (left == piles) - piles++; - top[left] = poker; - } - - return piles; - } -}; \ No newline at end of file diff --git a/C_plus/355*_DesignTwitter.cpp b/C_plus/355*_DesignTwitter.cpp deleted file mode 100644 index 819f348..0000000 --- a/C_plus/355*_DesignTwitter.cpp +++ /dev/null @@ -1,69 +0,0 @@ -class Twitter -{ -private: - // maintain two hash table ,and time to getNewsFeed 10 most recent tweet IDs - unordered_map > follows; // userID mapping userID of followeeId - unordered_map > posts; // userID mapping [time mapping postID] - int time; - -public: - /** Initialize your data structure here. */ - Twitter() - { - time = 0; - } - - /** Compose a new tweet. */ - void postTweet(int userId, int tweetId) - { - follow(userId, userId); - posts[userId][time++] = tweetId; - } - - /** Retrieve the 10 most recent tweet ids in the user's news feed. Each item in the news feed must be posted by users who the user followed or by the user herself. Tweets must be ordered from most recent to least recent. */ - vector getNewsFeed(int userId) - { - vector ret; - map m_top10; - for (int s : follows[userId]) - { - for (auto p : posts[s]) - { //traverse map - m_top10[p.first] = p.second; - // m_top10.insert({p.first, p.sacond}); - if (m_top10.size() > 10) - m_top10.erase(m_top10.begin()); - } - } - - for (auto m : m_top10) - { - ret.emplace(ret.begin(), m.second); - } - return ret; - } - - /** Follower follows a followee. If the operation is invalid, it should be a no-op. */ - void follow(int followerId, int followeeId) - { - follows[followerId].insert(followeeId); - } - - /** Follower unfollows a followee. If the operation is invalid, it should be a no-op. */ - void unfollow(int followerId, int followeeId) - { - if (followerId != followeeId) - { - follows[followerId].erase(followeeId); - } - } -}; - -/** - * Your Twitter object will be instantiated and called as such: - * Twitter* obj = new Twitter(); - * obj->postTweet(userId,tweetId); - * vector param_2 = obj->getNewsFeed(userId); - * obj->follow(followerId,followeeId); - * obj->unfollow(followerId,followeeId); - */ \ No newline at end of file diff --git a/C_plus/35_SearchInsertPosition.cpp b/C_plus/35_SearchInsertPosition.cpp deleted file mode 100644 index 7b5f2c6..0000000 --- a/C_plus/35_SearchInsertPosition.cpp +++ /dev/null @@ -1,40 +0,0 @@ -class Solution -{ -public: - int searchInsert(vector &nums, int target) - { - - // option 1 O(logn) binary search - // int l=0, r= nums.size()-1; - - // while(l<=r){ - // int mid = (l+r)/2; - - // if(target==nums[mid]) return mid; - // else if(target>nums[mid]) l = mid+1; - // else r = mid-1; - // } - // return l; - - - // binary search - // lower bound - int l= 0 , r = nums.size(); - while(l= target) - return i; - } - return nums.size(); - } -}; \ No newline at end of file diff --git a/C_plus/363*_MaxSumofRectangleNoLargerThanK.cpp b/C_plus/363*_MaxSumofRectangleNoLargerThanK.cpp deleted file mode 100644 index fb03ccb..0000000 --- a/C_plus/363*_MaxSumofRectangleNoLargerThanK.cpp +++ /dev/null @@ -1,31 +0,0 @@ -class Solution { -public: - int maxSumSubmatrix(vector>& matrix, int k) { - int m = matrix.size(), n = matrix[0].size() , ret = INT_MIN; - int sum[m][n]; - for(int i=0;i0) t+= sum[i-1][j]; - if(j>0) t+= sum[i][j-1]; - if (i > 0 && j > 0) t -= sum[i - 1][j - 1]; - sum[i][j] = t; - // cout< 0) d -= sum[r - 1][j]; - if (c > 0) d -= sum[i][c - 1]; - if (r > 0 && c > 0) d += sum[r - 1][c - 1]; - cout<= targetCapacity && targetCapacity % gcd(jug1Capacity, jug2Capacity) == 0) - return true; - return false; - } -}; \ No newline at end of file diff --git a/C_plus/367_ValidPerfectSquare.cpp b/C_plus/367_ValidPerfectSquare.cpp deleted file mode 100644 index 3089659..0000000 --- a/C_plus/367_ValidPerfectSquare.cpp +++ /dev/null @@ -1,28 +0,0 @@ -class Solution -{ -public: - bool isPerfectSquare(int num) - { - // option 1 O(sqrt(n)) - // for(int i =1;i<=num/i;i++){ - // if(i*i==num) return true; - // } - // return false; - - // option 2 O(sqrt(n)) - // 1 = 1 - // 4 = 1 + 3 - // 9 = 1 + 3 + 5 - // 16 = 1 + 3 + 5 + 7 - // 25 = 1 + 3 + 5 + 7 + 9 - int i = 1; - while (num > 0) - { - num -= i; - i += 2; - } - return num == 0; - - // option 3 binary search - } -}; \ No newline at end of file diff --git a/C_plus/36_ValidSudoku.cpp b/C_plus/36_ValidSudoku.cpp deleted file mode 100644 index e11e3e4..0000000 --- a/C_plus/36_ValidSudoku.cpp +++ /dev/null @@ -1,69 +0,0 @@ -class Solution -{ -public: - bool isValidSudoku(vector > &board) - { - - int m = board.size(), n = board[0].size(); - - for (int i = 0; i < n; ++i) - { - set s; - for (int j = 0; j < m; ++j) - { - if (board[i][j] != '.') - { - if (s.find(board[i][j]) != s.end()) - return false; - s.insert(board[i][j]); - } - } - } - - for (int j = 0; j < m; ++j) - { - set s; - for (int i = 0; i < n; ++i) - { - if (board[i][j] != '.') - { - if (s.find(board[i][j]) != s.end()) - return false; - s.insert(board[i][j]); - } - } - } - - vector > coor = { - {0, 0}, - {0, 1}, - {0, 2}, - {1, 0}, - {1, 1}, - {1, 2}, - {2, 0}, - {2, 1}, - {2, 2}, - }; - for (int i = 0; i < m; i += 3) - { - - for (int j = 0; j < n; j += 3) - { - set s; - for (pair p : coor) - { - int x = p.first + i; - int y = p.second + j; - if (board[x][y] != '.') - { - if (s.find(board[x][y]) != s.end()) - return false; - s.insert(board[x][y]); - } - } - } - } - return true; - } -}; \ No newline at end of file diff --git a/C_plus/37*_SudokuSolver.cpp b/C_plus/37*_SudokuSolver.cpp deleted file mode 100644 index 64387e3..0000000 --- a/C_plus/37*_SudokuSolver.cpp +++ /dev/null @@ -1,52 +0,0 @@ -class Solution -{ -public: - bool isValid(vector > &board, int r, int c, char n) - { - - for (int i = 0; i < 9; ++i) - { - - if (board[r][i] == n) - return false; - if (board[i][c] == n) - return false; - if (board[(r / 3) * 3 + i / 3][(c / 3) * 3 + i % 3] == n) - return false; - } - return true; - } - bool traverse(vector > &board, int r, int c) - { - int m = 9, n = 9; - if (c == n) - { - return traverse(board, r + 1, 0); - } - if (r == m) - return true; - - if (board[r][c] != '.') - { - return traverse(board, r, c + 1); - } - for (char ch = '1'; ch <= '9'; ++ch) - { - - if (!isValid(board, r, c, ch)) - continue; - - board[r][c] = ch; - if (traverse(board, r, c + 1)) - return true; - board[r][c] = '.'; - } - return false; - } - void solveSudoku(vector > &board) - { - - if (traverse(board, 0, 0)) - return; - } -}; \ No newline at end of file diff --git a/C_plus/371_SumOfTwoIntegers.cpp b/C_plus/371_SumOfTwoIntegers.cpp deleted file mode 100644 index 04964e4..0000000 --- a/C_plus/371_SumOfTwoIntegers.cpp +++ /dev/null @@ -1,53 +0,0 @@ -class Solution -{ -public: - int getSum(int a, int b) - { - // option 1 , sum == ^ & operation - // recurrent version - // if(b==0) return a; - // int sum = a^b; - // int carry = (a&b& 0x7fffffff)<<1; - // // 0x7fffffff = 2147483647 - // return getSum(sum, carry); - - // option 1 simplify one-line - return b == 0 ? a : getSum(a ^ b, (a & b & 0x7fffffff) << 1); - - // option 2 - // int sum, carry; - // while(b){ - // sum = a^b; - // carry = (a&b& 0x7fffffff)<<1; - // a=sum; - // b= carry; - // } - // return a; - - // option 2 simplify - int carry; - while (b) - { - carry = (a & b & 0x7fffffff) << 1; - a = a ^ b; - b = carry; - } - return a; - - - // option 3 - long long sum = 0, carry = 0; - long long ret = 0; - for(int i=0;i<32;++i){ - sum = carry; - sum += (a&1) + (b&1); - carry = sum/2; - sum %=2; - - ret += sum<>=1; - b>>=1; - } - return ret; - } -}; \ No newline at end of file diff --git a/C_plus/372*_SuperPow.cpp b/C_plus/372*_SuperPow.cpp deleted file mode 100644 index 26a5965..0000000 --- a/C_plus/372*_SuperPow.cpp +++ /dev/null @@ -1,32 +0,0 @@ -class Solution -{ -public: - int base = 1337; - int pow(int a, int k) - { - a %= base; - int res = 1; - for (int _ = 0; _ < k; _++) - { - // 這裡有乘法,可能溢位 - res *= a; - // 對每次乘法结果取餘數 - res %= base; - } - return res; - } - int superPow(int a, vector &b) - { - - // option 1 - // a = 2 , b = [1,2] , 2048 - // 2^2 * superPow(a, [1])^10 - // 2^2 * 2^10 = 2048 - if (b.empty()) - return 1; - int ret = pow(a, b.back()); - b.pop_back(); - ret *= pow(superPow(a, b), 10); - return ret % base; - } -}; \ No newline at end of file diff --git a/C_plus/374_GuessNumberHigherorLower.cpp b/C_plus/374_GuessNumberHigherorLower.cpp deleted file mode 100644 index 63a049d..0000000 --- a/C_plus/374_GuessNumberHigherorLower.cpp +++ /dev/null @@ -1,36 +0,0 @@ -/** - * Forward declaration of guess API. - * @param num your guess - * @return -1 if num is lower than the guess number - * 1 if num is higher than the guess number - * otherwise return 0 - * int guess(int num); - */ - -class Solution -{ -public: - int guessNumber(int n) - { - // time out - // for(int i=n;i>=1;i--){ - // if(guess(i)==0) return i; - // } - // return 1; - - // binary search - int l = 1, r = n; - while (l < r) - { - int mid = l + (r - l) / 2; - int eval = guess(mid); - if (eval == 0) - return mid; - else if (eval == -1) - r = mid - 1; - else - l = mid + 1; - } - return l; - } -}; \ No newline at end of file diff --git a/C_plus/376*_WiggleSubsequence.cpp b/C_plus/376*_WiggleSubsequence.cpp deleted file mode 100644 index bed97c6..0000000 --- a/C_plus/376*_WiggleSubsequence.cpp +++ /dev/null @@ -1,29 +0,0 @@ -class Solution -{ -public: - int wiggleMaxLength(vector &nums) - { - - // dp - // 1 7 4 9 2 5 - //up 1 2 2 4 2 6 - //down 1 1 3 1 5 5 - int n = nums.size(); - vector up(n, 1), down(n, 1); - for (int i = 1; i < n; ++i) - { - for (int j = 0; j < i; ++j) - { - if (nums[i] > nums[j]) - up[i] = max(down[j] + 1, up[i]); - else if (nums[i] < nums[j]) - down[i] = max(up[j] + 1, down[i]); - } - cout << up[i] << " " << down[i] << endl; - } - return max(up.back(), down.back()); - // option 2 greedy - - // int p = 1, q = 1, n = nums.size(); - } -}; \ No newline at end of file diff --git a/C_plus/377*_CombinationSumIV.cpp b/C_plus/377*_CombinationSumIV.cpp deleted file mode 100644 index cb3c09d..0000000 --- a/C_plus/377*_CombinationSumIV.cpp +++ /dev/null @@ -1,28 +0,0 @@ -class Solution -{ -public: - int combinationSum4(vector &nums, int target) - { - - // dp [1,2,3] 4 - // 0 1 2 3 4 - // 1 1 2 4 7 - - // [9] 3 - // 0 1 2 3 - // 1 0 0 0 - - // avoid overflow - vector dp(target + 1, 0); - dp[0] = 1; - for (int i = 1; i <= target; ++i) - { - for (auto a : nums) - { - if (i >= a) - dp[i] += dp[i - a]; - } - } - return dp.back(); - } -}; \ No newline at end of file diff --git a/C_plus/378*_KthSmallestElementinaSortedMatrix.cpp b/C_plus/378*_KthSmallestElementinaSortedMatrix.cpp deleted file mode 100644 index 7d9be4e..0000000 --- a/C_plus/378*_KthSmallestElementinaSortedMatrix.cpp +++ /dev/null @@ -1,70 +0,0 @@ -class Solution -{ -public: - int kthSmallest(vector > &matrix, int k) - { - - // option 1 brute O(n^3) -> time limited - // flatten and insert sort - // int m=matrix.size(), n=matrix[0].size(); - // vector vec(matrix[0].begin(), matrix[0].end()); - - // for(int i=1;i-1 && vec[j] >a){ - // vec[j+1] = vec[j]; - // j--; - // } - // vec[j+1] = a; - // } - // } - - // return vec[k-1]; - - // option 2 - // search matrix - // [1 5 90] - // [10 13 130] - // [12 103 150] , k=4 - // use STL - // priority_queue,greater > q; // 最小的優先取出 - // int m =matrix.size(), n=matrix[0].size(); - - // for(int i=0;i 小於 mid=8 數字有2個 - // 第一個元素大於 mid 12 的位置 6 - // 遍歷完,可以找出mid 中間數,是第幾小的數字 - if (cnt == k) - right = mid; - else if (cnt < k) - left = mid + 1; - else - right = mid; - } - return left; - } -}; \ No newline at end of file diff --git a/C_plus/380*_InsertDeleteGetRandomO(1).cpp b/C_plus/380*_InsertDeleteGetRandomO(1).cpp deleted file mode 100644 index a741537..0000000 --- a/C_plus/380*_InsertDeleteGetRandomO(1).cpp +++ /dev/null @@ -1,51 +0,0 @@ -class RandomizedSet { -private: - // 藉由hash 插入刪除都為O(1)的特性,紀錄索引 - unordered_map valToIndex; - vector nums; -public: - /** Initialize your data structure here. */ - RandomizedSet() { - } - - /** Inserts a value to the set. Returns true if the set did not already contain the specified element. */ - bool insert(int val) { - // O(1) - if(valToIndex.count(val)) return false; - - nums.push_back(val); - valToIndex[val] = nums.size()-1; - return true; - } - - /** Removes a value from the set. Returns true if the set contained the specified element. */ - bool remove(int val) { - // O(1),在數組中,要刪除元素與末端元素 先進行交換下進行刪除 - if(valToIndex.find(val) ==valToIndex.end() ) return false; - // 取得 val 的索引 - int i = valToIndex[val]; - // 修改 nums.back() 的索引成 val 的索引,因為稍後會對調 - valToIndex[nums.back()] = i; - - swap(nums[i] , nums.back()); - - nums.pop_back(); - // 刪除 val 對應的索引 - valToIndex.erase(val); - return true; - } - - /** Get a random element from the set. */ - int getRandom() { - // O(1) - return nums[rand() % nums.size()]; - } -}; - -/** - * Your RandomizedSet object will be instantiated and called as such: - * RandomizedSet* obj = new RandomizedSet(); - * bool param_1 = obj->insert(val); - * bool param_2 = obj->remove(val); - * int param_3 = obj->getRandom(); - */ \ No newline at end of file diff --git a/C_plus/382_LinkedListRandomNode.cpp b/C_plus/382_LinkedListRandomNode.cpp deleted file mode 100644 index 2b3fce5..0000000 --- a/C_plus/382_LinkedListRandomNode.cpp +++ /dev/null @@ -1,95 +0,0 @@ -/** - * Definition for singly-linked list. - * struct ListNode { - * int val; - * ListNode *next; - * ListNode() : val(0), next(nullptr) {} - * ListNode(int x) : val(x), next(nullptr) {} - * ListNode(int x, ListNode *next) : val(x), next(next) {} - * }; - */ - -// option 1 -// class Solution { -// private: -// int len; -// ListNode *head ; -// public: -// /** @param head The linked list's head. -// Note that the head is guaranteed to be not null, so it contains at least one node. */ -// Solution(ListNode* head) { -// this->head = head; -// len = 0; -// for(ListNode *p = head; p;p=p->next) len++; -// } - -// /** Returns a random node's value. */ -// int getRandom() { -// /* 產生 [min , max] 的整數亂數 */ - -// ListNode *p = head; -// int randomer = rand() % len; -// for(randomer = randomer;randomer>0;randomer--){ -// p=p->next; -// } -// return p->val; -// } -// }; - -/** - * Your Solution object will be instantiated and called as such: - * Solution* obj = new Solution(head); - * int param_1 = obj->getRandom(); - */ - -// option 2 水塘抽样 Reservoir Sampling -class Solution -{ -private: - ListNode *head; - -public: - /** @param head The linked list's head. - Note that the head is guaranteed to be not null, so it contains at least one node. */ - Solution(ListNode *head) - { - this->head = head; - } - - /** Returns a random node's value. */ - int getRandom() - { - - int i = 0, ret = 0; - ListNode *p = head; - while (p) - { - i++; - // rand()%i 相當於 生成 [0,i) 的整數 - // rand()%i ==0 相當於 這個整數等於0 的機率是 1/i - if (rand() % i == 0) - ret = p->val; - p = p->next; - } - return ret; - } -}; - - -// option 3 - -class Solution { -private: - vector vec; - int size =0; -public: - Solution(ListNode* head) { - for(ListNode *p =head;p; p=p->next){ - vec.push_back(p->val); - size++; - } - } - int getRandom() { - return vec[rand()%size]; - } -}; diff --git a/C_plus/383_RansomNote.cpp b/C_plus/383_RansomNote.cpp deleted file mode 100644 index 9a35ad5..0000000 --- a/C_plus/383_RansomNote.cpp +++ /dev/null @@ -1,30 +0,0 @@ -class Solution -{ -public: - bool canConstruct(string ransomNote, string magazine) - { - // option 1 - // if(ransomNote.size() > magazine.size()) return false; - // vector vec(26,0); // you can also use map - // for(char c:magazine) vec[c-'a']++; - // for(char c:ransomNote){ - // if(vec[c-'a']==0) return false; - // vec[c-'a']--; - // } - // return true; - - // option 2 - map m; - if (ransomNote.size() > magazine.size()) - return false; - for (char a : magazine) - m[a]++; - for (char a : ransomNote) - { - m[a]--; - if (m[a] < 0) - return false; - } - return true; - } -}; \ No newline at end of file diff --git a/C_plus/384*_ShuffleanArray.cpp b/C_plus/384*_ShuffleanArray.cpp deleted file mode 100644 index 80a3ee8..0000000 --- a/C_plus/384*_ShuffleanArray.cpp +++ /dev/null @@ -1,37 +0,0 @@ -class Solution -{ -private: - vector v; - -public: - Solution(vector nums) : v(nums) {} - - /** Resets the array to its original configuration and return it. */ - vector reset() - { - return v; - } - - /** Returns a random shuffling of the array. */ - vector shuffle() - { - // knuth-shuffle: - //https://yjk94.wordpress.com/2017/03/17/%E6%B4%97%E7%89%8C%E7%9A%84%E6%AD%A3%E7%A1%AE%E5%A7%BF%E5%8A%BF-knuth-shuffle%E7%AE%97%E6%B3%95/ - - vector ret = v; - int n = ret.size(); - for(int i=0;i param_1 = obj->reset(); - * vector param_2 = obj->shuffle(); - */ \ No newline at end of file diff --git a/C_plus/387_FirstUniqueCharacterInaString.cpp b/C_plus/387_FirstUniqueCharacterInaString.cpp deleted file mode 100644 index 53d0a9c..0000000 --- a/C_plus/387_FirstUniqueCharacterInaString.cpp +++ /dev/null @@ -1,57 +0,0 @@ -class Solution -{ -public: - int firstUniqChar(string s) - { - - // option 1 - // map m; - // for(int i=0;i m; - // for(char c:s) m[c]++; - // for(int i=0;i v(26, 0); - for (char c : s) - v[c - 'a']++; - for (int i = 0; i < s.size(); ++i) - { - if (v[s[i] - 'a'] == 1) - return i; - } - return -1; - - - // option 3 - // vector to recorder last index - // O(n) time and O(1) space - int n = s.size(); - vector vec(26,0); - for(int i=0;i v(26,0); - // for(char c:s) v[c-'a']++; - - // for(char c:t){ - // v[c-'a']--; - // } - // for(int i=0;i<26;++i){ - // if(v[i]!=0) { - // return char(i+'a'); - // } - // } - // return ' '; - - // option 2 ret ^a; - // int ret = 0; - // for(char c:s) ret ^= (c-'a'); - // for(char c:t) ret ^= (c-'a'); - // return char(ret+'a'); - - // option 3 用減法,ascii 字母分別代表個字的數字 - char ret = 0; - for (char c : s) - ret -= c; - for (char c : t) - ret += c; - return ret; - } -}; \ No newline at end of file diff --git a/C_plus/38_CountandSay.cpp b/C_plus/38_CountandSay.cpp deleted file mode 100644 index eec4dc7..0000000 --- a/C_plus/38_CountandSay.cpp +++ /dev/null @@ -1,36 +0,0 @@ -class Solution -{ -public: - string say(string str) - { - int count = 1; - char c = str[0]; - int j = 1; - string ret = ""; - for (j = 1; j < str.size(); ++j) - { - if (str[j] == c) - count++; - else if (str[j] != c) - { - ret += (to_string(count) + str[j - 1]); - count = 1; - c = str[j]; - } - } - - ret += (to_string(count) + str[j - 1]); - return ret; - } - string countAndSay(int n) - { - string ret = "1"; - for (int i = 2; i <= n; ++i) - { - - ret = say(ret); - } - - return ret; - } -}; \ No newline at end of file diff --git a/C_plus/39*_CombinationSum.cpp b/C_plus/39*_CombinationSum.cpp deleted file mode 100644 index faca2c8..0000000 --- a/C_plus/39*_CombinationSum.cpp +++ /dev/null @@ -1,29 +0,0 @@ -class Solution -{ -public: - vector > ret; - void traverse(vector &cand, int target, int l, int r, vector &path) - { - if (target < 0) - return; - - if (target == 0) - { - ret.push_back(path); - return; - } - - for (int i = l; i <= r; ++i) - { - path.push_back(cand[i]); - traverse(cand, target - cand[i], i, r, path); - path.pop_back(); - } - } - vector > combinationSum(vector &candidates, int target) - { - vector path; - traverse(candidates, target, 0, candidates.size() - 1, path); - return ret; - } -}; \ No newline at end of file diff --git a/C_plus/391*_PerfectRectangle.cpp b/C_plus/391*_PerfectRectangle.cpp deleted file mode 100644 index 3d5d3cc..0000000 --- a/C_plus/391*_PerfectRectangle.cpp +++ /dev/null @@ -1,64 +0,0 @@ -class Solution -{ -public: - bool isRectangleCover(vector > &rectangles) - { - - // option 最終形成的圖形有多少頂點,就能判斷最終圖形是不是完美矩形 - // 當某點同時是 2 個 或 4 個矩形的頂點時,該點最終不是頂點。 - // (X1, Y1) 左下角頂點 (X2, Y2) 右上角頂點 - int X1 = INT_MAX, Y1 = INT_MAX; - int X2 = INT_MIN, Y2 = INT_MIN; - // 用集合紀錄最終圖形的頂點 - set > points; - // 所有小矩形面積 - int actual_area = 0; - for (vector r : rectangles) - { - int x1 = r[0], y1 = r[1], x2 = r[2], y2 = r[3]; - X1 = min(X1, x1); - Y1 = min(Y1, y1); - X2 = max(X2, x2); - Y2 = max(Y2, y2); - actual_area += (x2 - x1) * (y2 - y1); - - // 對於每個點,如果存在集合中,則刪除他。 如果不存在集合中,添加他 - // 在集合中剩下的點都是出現奇數次的點 - // 记录最终形成的图形中的顶点 - vector > pts = { - make_tuple(x1, y1), - make_tuple(x1, y2), - make_tuple(x2, y1), - make_tuple(x2, y2)}; - for (tuple pt : pts) - { - if (points.find(pt) != points.end()) - points.erase(pt); - else - points.insert(pt); - } - } - - // 計算完美矩形的理論面積 - int expected_area = (X2 - X1) * (Y2 - Y1); - // 面積應該相同 - if (actual_area != expected_area) - { - return false; - } - // 判断最终留下的顶点个数是否为 4 - if (points.size() != 4) - return false; - // 判断留下的 4 个顶点是否是完美矩形的顶点 - if (points.find(make_tuple(X1, Y1)) == points.end()) - return false; - if (points.find(make_tuple(X1, Y2)) == points.end()) - return false; - if (points.find(make_tuple(X2, Y1)) == points.end()) - return false; - if (points.find(make_tuple(X2, Y2)) == points.end()) - return false; - - return true; - } -}; \ No newline at end of file diff --git a/C_plus/392_IsSubsequence.cpp b/C_plus/392_IsSubsequence.cpp deleted file mode 100644 index 1ab59a6..0000000 --- a/C_plus/392_IsSubsequence.cpp +++ /dev/null @@ -1,80 +0,0 @@ -class Solution -{ -public: - bool isSubsequence(string s, string t) - { - // option 1 dp O(NM) time and O(NM) space - // a h b g d c - - //a 1 1 1 1 1 1 - //b 1 1 2 2 2 2 - //c 1 1 2 2 2 3 - - // int m = s.size(), n = t.size(); - - // vector> dp(m+1, vector(n+1,0)); - - // for(int i=1;i<=m;++i){ - // for(int j = 1;j<=n ;++j){ - - // if(s[i-1] == t[j-1]) dp[i][j] = dp[i-1][j-1] +1; - // else dp[i][j] = max(dp[i-1][j], dp[i][j-1]); - - // } - // } - // return dp[m][n]==s.size(); - - // option 2 O(N) time , N 為 t的長度 - - // int l = 0; - // for(int i=0;i > index(256); - for (int i = 0; i < n; ++i) - { - char c = t[i]; - // if(index[c] == nullptr) index[c] = list(); - index[c].push_back(i); - } - - vector temp; - int j = 0; // 指向t字串索引 - // 借助index 查找 s[i] - for (int i = 0; i < m; ++i) - { - char c = s[i]; - if (index[c] == temp) - return false; - int pos = left_bound(index[c], j); - cout << j << " " << pos << endl; - if (pos == index[c].size()) - return false; - - j = index[c][pos] + 1; - } - return true; - } - int left_bound(vector &arr, int tar) - { - int lo = 0, hi = arr.size(); - while (lo < hi) - { - int mid = lo + (hi - lo) / 2; - if (tar > arr[mid]) - lo = mid + 1; - else - hi = mid; - } - - return lo; - } -}; \ No newline at end of file diff --git a/C_plus/394*_DecodeString.cpp b/C_plus/394*_DecodeString.cpp deleted file mode 100644 index e83aa57..0000000 --- a/C_plus/394*_DecodeString.cpp +++ /dev/null @@ -1,47 +0,0 @@ -class Solution -{ -public: - string decodeString(string s) - { - // option 1 - // iterative + stack - stack nums; - stack strs; - string t = ""; - int cnt = 0; - for (int i = 0; i < s.size(); ++i) - { - if (s[i] >= '0' && s[i] <= '9') - { - cnt = 10 * cnt + s[i] - '0'; - } - else if (s[i] == '[') - { - nums.push(cnt); - strs.push(t); - t.clear(); - cnt = 0; - } - else if (s[i] == ']') - { - int k = nums.top(); - nums.pop(); - for (int j = 0; j < k; ++j) - { - strs.top() += t; - } - t = strs.top(); - strs.pop(); - } - else - { - // char - t += s[i]; - } - } - - return strs.empty() ? t : strs.top(); - - // recursive + 自帶 stack - } -}; \ No newline at end of file diff --git a/C_plus/396*_RotateFunction.cpp b/C_plus/396*_RotateFunction.cpp deleted file mode 100644 index 5e97051..0000000 --- a/C_plus/396*_RotateFunction.cpp +++ /dev/null @@ -1,45 +0,0 @@ -class Solution -{ -public: - int maxRotateFunction(vector &nums) - { - // option 0 O(n^2) time out - // int n= nums.size(); - // int ret = INT_MIN; - // for(int i=0;i=n) k=0; - // f += k*a; - // k++; - // } - // ret = max(ret, f); - // } - // return ret; - - // option 1 math - int total = 0, f = 0, n = nums.size(); - for (int i = 0; i < n; ++i) - { - total += nums[i]; - f += (i * nums[i]); - } - int ret = f; - // f_0 = 0A + 1B + 2C + 3D - // f_1 = 0D + 1A + 2B + 3C - // f_2 = 0C + 1D + 2A + 3B - // f_3 = 0B + 1C + 2D + 3A - // sum = 1A + 1B + 1C + 1D - // f_1 = f_0 + sum - 4D - // f_2 = f_1 + sum - 4C - // f_3 = f_2 + sum - 4B - // f(i) = f(i-1) + sum - n*A[n-i]; - for (int i = 1; i < n; ++i) - { - f = f + total - n * nums[n - i]; - ret = max(ret, f); - } - return ret; - } -}; \ No newline at end of file diff --git a/C_plus/397*_IntegerReplacement.cpp b/C_plus/397*_IntegerReplacement.cpp deleted file mode 100644 index b731840..0000000 --- a/C_plus/397*_IntegerReplacement.cpp +++ /dev/null @@ -1,38 +0,0 @@ -class Solution -{ -public: - unordered_map memo; - int integerReplacement(int n) - { - - // option 1 - // if(n==1) return 0; - // long long t = n; - // if(n%2==0)return 1+ integerReplacement(t/2); - - // // avoid overflow - // else return 2+min(integerReplacement((t-1)/2), integerReplacement((t+1)/2)); - - // option 1.1 memo pattern to faster - // if(n==1) return 0; - // if(memo.count(n)) return memo[n]; - // long long t = n; - // if(n%2==0) memo[n] = 1+ integerReplacement(t/2); - // // avoid overflow - // else memo[n] = 2+min(integerReplacement((t-1)/2), integerReplacement((t+1)/2)); - // return memo[n]; - - // option 2 dp time out - // 0 1 2 3 4 5 6 7 8 - // 0 0 1 2 2 3 3 4 3 - vector dp(n + 1, 0); - for (int i = 2; i <= n; ++i) - { - if (i % 2 == 0) - dp[i] = 1 + dp[i / 2]; - else - dp[i] = 1 + min(dp[(i - 1)], 1 + dp[(i / 2 + 1)]); - } - return dp[n]; - } -}; \ No newline at end of file diff --git a/C_plus/398*_RandomPickIndex.cpp b/C_plus/398*_RandomPickIndex.cpp deleted file mode 100644 index 63b9e86..0000000 --- a/C_plus/398*_RandomPickIndex.cpp +++ /dev/null @@ -1,47 +0,0 @@ -class Solution -{ -private: - vector vec; - int size = 0; - -public: - Solution(vector &nums) - { - // option 1 水塘抽樣 - // 從S中抽取首k項放入「水塘」中 - // 對於每一個S[j]項(j ≥ k): - // 隨機產生一個範圍從0到j的整數r - // 若 r < k 則把水塘中的第r項換成S[j]項 - this->vec = nums; - size = vec.size(); - } - - int pick(int target) - { - - int cnt = 0, ret = -1; - for (int i = 0; i < vec.size(); ++i) - { - if (vec[i] != target) - continue; - cnt++; - if (rand() % cnt == 0) - ret = i; - } - - return ret; - - // option 2 - int i = rand()%size; - while(vec[i]!=target){ - i = rand()%size; - } - return i; - } -}; - -/** - * Your Solution object will be instantiated and called as such: - * Solution* obj = new Solution(nums); - * int param_1 = obj->pick(target); - */ \ No newline at end of file diff --git a/C_plus/3_LongestSubtringWithoutRpeatingCharacters.cpp b/C_plus/3_LongestSubtringWithoutRpeatingCharacters.cpp deleted file mode 100644 index c4e2073..0000000 --- a/C_plus/3_LongestSubtringWithoutRpeatingCharacters.cpp +++ /dev/null @@ -1,61 +0,0 @@ -class Solution -{ -public: - int lengthOfLongestSubstring(string s) - { - // option 1 slid window O(n) time and O(n) space worst case - - // int left = 0, right = 0; - // unordered_map window; - // int ret = 0; - // while(right 1){ - // char d = s[left]; - // left++; - // window[d]--; - - // } - // ret = max(ret, right - left); - - // } - // return ret; - - // option 2 - vector window(128, 0); - int l = 0, r = 0, ans = 0; - while (r < s.size()) - { - char c = s[r++]; - - window[c]++; - while (window[c] > 1) - { - char d = s[l++]; - window[d]--; - } - ans = max(ans, r - l); - } - return ans; - - // n^2 logn brute force - int res = 0; - for (int i = 0; i < s.size(); ++i) - { - set tmp; - for (int j = i; j < s.size(); ++j) - { - if (tmp.find(s[j]) != tmp.end()) - break; - else - tmp.insert(s[j]); - } - res = max(res, int(tmp.size())); - } - return res; - } -}; \ No newline at end of file diff --git a/C_plus/40*_CombinationSUmII.cpp b/C_plus/40*_CombinationSUmII.cpp deleted file mode 100644 index 3afabbf..0000000 --- a/C_plus/40*_CombinationSUmII.cpp +++ /dev/null @@ -1,30 +0,0 @@ -class Solution -{ -public: - vector > combinationSum2(vector &candidates, int target) - { - sort(candidates.begin(), candidates.end()); - vector comb; - vector > ret; - combinationSum2(candidates, target, comb, ret, 0); - return ret; - } - void combinationSum2(vector &candidates, int target, vector &comb, vector > &ret, int begin) - { - if (!target) - { - ret.push_back(comb); - return; - } - for (int i = begin; i < candidates.size() && target >= candidates[i]; i++) - { - // if(i> l && candidates[i] == candidates[i-1]) continue; - if (i == begin || candidates[i] != candidates[i - 1]) - { - comb.push_back(candidates[i]); - combinationSum2(candidates, target - candidates[i], comb, ret, i + 1); - comb.pop_back(); - } - } - } -}; \ No newline at end of file diff --git a/C_plus/401*_BinaryWatch.cpp b/C_plus/401*_BinaryWatch.cpp deleted file mode 100644 index 9e5585f..0000000 --- a/C_plus/401*_BinaryWatch.cpp +++ /dev/null @@ -1,28 +0,0 @@ -class Solution -{ -public: - vector readBinaryWatch(int turnedOn) - { - - // 用bitset 將任意進制數轉換為二進制,coun統計 1 的個數 - vector ret; - for (int h = 0; h < 12; ++h) - { - for (int m = 0; m < 60; ++m) - { - // (h<<6 ) avoid minute , so hour shift 64 = 2^6 - if (bitset<10>((h << 6) + m).count() == turnedOn) - { - string cand = to_string(h); - if (m < 10) - cand += ":0"; - else - cand += ":"; - cand += to_string(m); - ret.push_back(cand); - } - } - } - return ret; - } -}; \ No newline at end of file diff --git a/C_plus/402*_RemoveKDigits.cpp b/C_plus/402*_RemoveKDigits.cpp deleted file mode 100644 index a37198a..0000000 --- a/C_plus/402*_RemoveKDigits.cpp +++ /dev/null @@ -1,28 +0,0 @@ -class Solution -{ -public: - string removeKdigits(string num, int k) - { - - string ret; - int keep = num.size() - k; - for (int i = 0; i < num.size(); ++i) - { - - while (!ret.empty() && ret.back() > num[i] && k) - { - ret.pop_back(); - k--; - } - ret += num[i]; //push_back - } - - ret.resize(keep); // ret.erase(keep, string::npos); - int s = 0; - while (ret[s] == '0' && s < ret.size()) - s++; - ret.erase(0, s); - - return ret == "" ? "0" : ret; - } -}; \ No newline at end of file diff --git a/C_plus/404*_SumofLeftLeaves.cpp b/C_plus/404*_SumofLeftLeaves.cpp deleted file mode 100644 index 8fe6339..0000000 --- a/C_plus/404*_SumofLeftLeaves.cpp +++ /dev/null @@ -1,40 +0,0 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution -{ -public: - // void findLeftLeave(TreeNode *root, vector & ret){ - void findLeftLeave(TreeNode *root, int &ans) - { - if (root == nullptr) - return; - if (root->left && root->left->left == nullptr && root->left->right == nullptr) - { - // ret.push_back(root->left->val); - ans += root->left->val; - } - findLeftLeave(root->left, ans); - findLeftLeave(root->right, ans); - } - int sumOfLeftLeaves(TreeNode *root) - { - // option 1 維護一個變量或vector 紀錄left leaves 的總和或是所有left leaves,inorder - if (root->left == nullptr && root->right == nullptr) - return 0; - vector ret; - int ans = 0; - findLeftLeave(root, ans); - - // for(auto r:ret) ans+=r; - return ans; - } -}; \ No newline at end of file diff --git a/C_plus/405*_ConvertaNumbertoHexadecimal.cpp b/C_plus/405*_ConvertaNumbertoHexadecimal.cpp deleted file mode 100644 index 6cb1408..0000000 --- a/C_plus/405*_ConvertaNumbertoHexadecimal.cpp +++ /dev/null @@ -1,25 +0,0 @@ -class Solution -{ -public: - string toHex(int num) - { - string ret, hex = "0123456789abcdef"; - unsigned int x = num; - while (x > 0) - { - ret = hex[x % 16] + ret; - x /= 16; - } - return ret.empty() ? "0" : ret; - - // bit manuipulation - // string ret, str= "0123456789abcdef"; - // int cnt = 0; - // while (num != 0 && cnt++ < 8){ - // // for(int i =0;i<8;++i){ - // ret = str[num& 15]+ret; - // num >>=4; - // } - // return ret==""? "0": ret; - } -}; \ No newline at end of file diff --git a/C_plus/410*_SplitArrayLargestSum.cpp b/C_plus/410*_SplitArrayLargestSum.cpp deleted file mode 100644 index 1e88102..0000000 --- a/C_plus/410*_SplitArrayLargestSum.cpp +++ /dev/null @@ -1,77 +0,0 @@ -class Solution -{ -public: - int split(vector &nums, int max) - { - // 定義: 在每個子數組和不超過 max 的條件下,計算nums 至少可以分割成多少的子數組 - // 單調遞減 函數 - // f(nums, 10) = 3 - // 7 2 5 10 , max = 10 - // [7,2] [5] [10] return 3 - // O(N) - int count = 1; - int sum = 0; - for (int i = 0; i < nums.size(); ++i) - { - if (sum + nums[i] > max) - { - // 當前 子數組和大於max 限制,則子數組不能再添加元素 - count++; - sum = nums[i]; - } - else - { - // 當前子數組和 還未到達 max 限制,繼續添加元素 - sum += nums[i]; - } - } - return count; - } - int splitArray(vector &nums, int m) - { - - // 最大子數組 取值範圍 必定是 閉區間 [maxs(nums), sum(nums)] - int left = 0, right = 0; - for (int n : nums) - { - left = max(left, n); - right += n; - } - // option 1 窮舉法 - // for(int max= left; max<=right; ++max ){ - // // 如果最大子數組是和是 max - // // 至少可以把nums 分成 n 個子數組 - // int n= split(nums, max); - // if (n<=m) return max; - // } - - // option 2 O(NlogS) - // O(logS) - right++; // 左閉右開所以right +1 - while (left < right) - { - // mid 代表 最大子數組和 - int mid = left + (right - left) / 2; - int target = split(nums, mid); - // 左側邊界 二元搜尋 - // 如果最大子數組是和是 mid, 至少可以把nums 分成target 個子數組 - - if (target == m) - { - // 收縮右邊界,達到搜尋左邊界的目的 - right = mid; - } - else if (target < m) - { - // 最大子數組和 小於 m ,代表 最大子數組是和 mid上限高了,以致於 target < m,所以mid 減小一些 - right = mid; - } - else if (target > m) - { - left = mid + 1; - } - } - - return left; - } -}; \ No newline at end of file diff --git a/C_plus/412_FizzBuzz.cpp b/C_plus/412_FizzBuzz.cpp deleted file mode 100644 index 5eeb4fd..0000000 --- a/C_plus/412_FizzBuzz.cpp +++ /dev/null @@ -1,20 +0,0 @@ -class Solution -{ -public: - vector fizzBuzz(int n) - { - vector ret(n, ""); - for (int i = 1; i <= n; ++i) - { - if (i % 15 == 0) - ret[i - 1] = "FizzBuzz"; - else if (i % 5 == 0) - ret[i - 1] = "Buzz"; - else if (i % 3 == 0) - ret[i - 1] = "Fizz"; - else - ret[i - 1] = to_string(i); - } - return ret; - } -}; \ No newline at end of file diff --git a/C_plus/413*_ArithmeticSlices.cpp b/C_plus/413*_ArithmeticSlices.cpp deleted file mode 100644 index cc5bb94..0000000 --- a/C_plus/413*_ArithmeticSlices.cpp +++ /dev/null @@ -1,44 +0,0 @@ -class Solution -{ -public: - int numberOfArithmeticSlices(vector &nums) - { - // 1 2 3 4 5 6 - // 0 0 1 2 3 4 - - // 1 3 5 7 9 11 13 - // 0 0 1 2 3 4 5 - - // 1 2 3 8 9 10 - // 0 0 1 0 0 1 - - // option 1 dp - // int n = nums.size(); - // vector dp(n,0); - // int ret = 0; - // for(int i=2;i &nums) - { - int first = 0, second = 0, third = 0; - long max_1 = LONG_MIN, max_2 = LONG_MIN, max_3 = LONG_MIN; - for (int n : nums) - { - if (n == max_1 || n == max_2 || n == max_3) - continue; - - if (n > max_1) - { - max_3 = max_2; - max_2 = max_1; - max_1 = n; - } - else if (n > max_2) - { - max_3 = max_2; - max_2 = n; - } - else if (n > max_3) - { - max_3 = n; - } - } - - return max_3 == LONG_MIN ? max_1 : max_3; - } -}; \ No newline at end of file diff --git a/C_plus/415*_AddStrings.cpp b/C_plus/415*_AddStrings.cpp deleted file mode 100644 index b0a5152..0000000 --- a/C_plus/415*_AddStrings.cpp +++ /dev/null @@ -1,22 +0,0 @@ -class Solution -{ -public: - string addStrings(string num1, string num2) - { - string ret = ""; - int n = num1.size(), m = num2.size(); - int l = n - 1, r = m - 1; - int carry = 0; - while (l > -1 || r > -1 || carry) - { - int sum = carry; - if (l > -1) - sum += num1[l--] - '0'; - if (r > -1) - sum += num2[r--] - '0'; - ret.insert(0, to_string(sum % 10)); - carry = sum / 10; - } - return ret; - } -}; \ No newline at end of file diff --git a/C_plus/416*_PartitionEqualSubsetSum.cpp b/C_plus/416*_PartitionEqualSubsetSum.cpp deleted file mode 100644 index 8a3b829..0000000 --- a/C_plus/416*_PartitionEqualSubsetSum.cpp +++ /dev/null @@ -1,106 +0,0 @@ -class Solution -{ -public: - bool canPartition(vector &nums) - { - // 0-1 背包問題 - // 狀態 = 背包重量 與 可選擇物品 - // int[][] dp[N+1][W+1] // N+1 前n+1個物品 W+1 w背包容量 - // dp[0][..] = 0 - // dp[..][0] = 0 - - // for i in [1..N]: - // for w in [1..W]: - // dp[i][w] = max( - // 把物品 i 装进背包, - // 不把物品 i 装进背包 - // ) - // return dp[N][W] - - // 可容納重量為 sum/2 的背包,有n個物品,每個物品重量為nums[i] - - - // 維護一個dp,表示數組是否能取出若干個數,其和為i - // nums[i-1] 第i個物品重量 - // dp[i - 1][j-nums[i-1]] 裝了第i個物品,背包剩餘重量 j - nums[i-1] 限制下能否被裝滿 - // 0 1 2 3 4 5 6 7 8 9 10 11 , target = 11 - // t f f f f f f f f f f f - // 1 t t f f f f f f f f f f - // 5 t t f f f t t f f f f f - // 11 t t f f f t t f f f f t - // 5 t t f f f t t f f f t t - // int sum = accumulate(nums.begin(), nums.end(), 0); - // // 總和為奇數,不可能分割成兩個相等集合 - // if(sum &1) return false; - // int target = sum/2, n = nums.size(); - // vector> dp(n+1, vector(target+1, false)); - // // base case - // for(int i=0;i<=n;++i) dp[i][0] = true; - - // for(int i= 1;i<=n;++i){ - // for(int j =1;j<=target ;++j){ - // if( j- nums[i-1] < 0){ - // // 背包容量不足,不能再裝第i個物品 - // dp[i][j] = dp[i-1][j]; - // } - // else{ - // //裝或不裝入背包 - // dp[i][j] = dp[i-1][j] || dp[i-1][j-nums[i-1]]; - // } - // } - // } - - // return dp[n][target]; - - // option 2 壓縮dp - int sum = 0, n = nums.size(); - for (int n : nums) - sum += n; - if (sum % 2 != 0) - return false; - sum /= 2; - vector dp(sum + 1, false); - dp[0] = true; - for (int i = 0; i < n; ++i) - { - for (int j = sum; j >= 0; j--) - { - // 背包問題 一維dp 須反向搜尋 - if (j - nums[i] >= 0) - dp[j] = dp[j] || dp[j - nums[i]]; - } - } - return dp[sum]; - - // dp but time out - int total = 0; - for(int n:nums) total +=n; - if(total%2!=0) return false; - int n = nums.size(); - vector used(n, false); - return dp(nums, total/2,0, 0, 2, used); - } - - - bool dp(vector &nums, int target, int s , int cur, int k, vector & used){ - // time error - int n= nums.size(); - if(k==0) return true; - if(cur == target) return dp(nums, target, 0, 0, k-1, used); - - - for(int i =s;i target) continue; - used[i] = true; - cur += nums[i]; - if(dp(nums, target, i+1, cur, k, used) ) return true; - used[i] = false; - cur -= nums[i]; - } - - return false; - } - -}; \ No newline at end of file diff --git a/C_plus/41_FirstMissingPositive.cpp b/C_plus/41_FirstMissingPositive.cpp deleted file mode 100644 index 2ff3d33..0000000 --- a/C_plus/41_FirstMissingPositive.cpp +++ /dev/null @@ -1,33 +0,0 @@ -class Solution -{ -public: - int firstMissingPositive(vector &nums) - { - // option 1 O(nlogn) time and O(1) space - // sort and compare - // int ret = 1; - // sort(nums.begin(), nums.end()); - // int n= nums.size(); - // for(int i=0;i0) { - // if(ret==nums[i]) ret++; - // } - // } - // return ret; - - // option 1 O(n) time and O(n) time - int n = nums.size(); - vector vec(n + 1, 0); - for (int i = 0; i < n; ++i) - { - if (nums[i] > 0 && nums[i] < n + 1) - vec[nums[i]]++; - } - for (int i = 1; i < vec.size(); ++i) - { - if (vec[i] == 0) - return i; - } - return vec.size(); - } -}; \ No newline at end of file diff --git a/C_plus/42*_TrappingRainWater.cpp b/C_plus/42*_TrappingRainWater.cpp deleted file mode 100644 index be0d773..0000000 --- a/C_plus/42*_TrappingRainWater.cpp +++ /dev/null @@ -1,97 +0,0 @@ -class Solution { -public: - int trap(vector& height) { - - // option 1 brute force O(n^2) time, O(1) space - // water[i] = min( - // # 左边最高的柱子 - // max(height[0..i]), - // # 右边最高的柱子 - // max(height[i..end]) - // ) - height[i] - -// int ret = 0; -// int n = height.size(); -// for(int i=1;i-1 ; j--){ -// l_max = max(l_max, height[j]); -// } - -// ret += min(l_max, r_max ) - height[i]; - -// } -// return ret; - - - // option 2 memo pattern O(n) space - // 提前計算l_max r_max -// if(height.empty()) return 0; -// int n = height.size(); -// vector l_max(n, 0) , r_max(n,0); -// l_max[0] = height[0], r_max[n-1]= height[n-1]; -// for(int i=1;i=1;--i){ -// r_max[i] = max(r_max[i+1], height[i]); -// } - -// int ret = 0; -// for(int i=1;i sta; //存索引 單調堆疊 -// int ret=0; -// for(int i=0;i children; - - Node() {} - - Node(int _val) { - val = _val; - } - - Node(int _val, vector _children) { - val = _val; - children = _children; - } -}; -*/ - -class Solution -{ -public: - vector > levelOrder(Node *root) - { - vector > ret; - if (!root) - return {}; - queue q; - q.push(root); - while (!q.empty()) - { - int size = q.size(); - vector temp; - for (int i = 0; i < size; ++i) - { - Node *p = q.front(); - q.pop(); - temp.push_back(p->val); - - for (Node *x : p->children) - { - q.push(x); - } - } - ret.push_back(temp); - } - return ret; - } -}; \ No newline at end of file diff --git a/C_plus/43*_MultiplyStrings.cpp b/C_plus/43*_MultiplyStrings.cpp deleted file mode 100644 index 862b354..0000000 --- a/C_plus/43*_MultiplyStrings.cpp +++ /dev/null @@ -1,28 +0,0 @@ -class Solution -{ -public: - string multiply(string num1, string num2) - { - int n = num1.size(), m = num2.size(); - vector ret(n + m, 0); - int carry = 0; - for (int i = n - 1; i > -1; i--) - { - for (int j = m - 1; j > -1; j--) - { - int p1 = i + j, p2 = i + j + 1; - int mul = (num1[i] - '0') * (num2[j] - '0') + ret[p2]; - ret[p2] = mul % 10; - ret[p1] += mul / 10; - } - } - string ans; - int i = 0; - while (i < ret.size() && ret[i] == 0) - i++; - for (int j = i; j < ret.size(); ++j) - ans += ret[j] + '0'; - return ans == "" ? "0" : ans; - } -}; -; diff --git a/C_plus/430_ FlattenaMultilevelDoublyLinkedList.cpp b/C_plus/430_ FlattenaMultilevelDoublyLinkedList.cpp deleted file mode 100644 index afb1561..0000000 --- a/C_plus/430_ FlattenaMultilevelDoublyLinkedList.cpp +++ /dev/null @@ -1,54 +0,0 @@ -/* -// Definition for a Node. -class Node { -public: - int val; - Node* prev; - Node* next; - Node* child; -}; -*/ - -class Solution -{ -public: - Node *flatten(Node *head) - { - if (!head) - return head; - stack sta; - Node *cur = head; - while (cur->next || cur->child) - { - if (cur->child) - { - if (cur->next) - { - sta.push(cur->next); - cur->next->prev = nullptr; - } - - cur->child->prev = cur; - cur->next = cur->child; - cur->child = nullptr; - } - cout << cur->val << " "; - cur = cur->next; - } - - while (!sta.empty()) - { - Node *p = sta.top(); - sta.pop(); - cur->next = p; - p->prev = cur; - while (cur->next) - { - - cur = cur->next; - } - } - - return head; - } -}; \ No newline at end of file diff --git a/C_plus/433_MinimumGeneticMutation.cpp b/C_plus/433_MinimumGeneticMutation.cpp deleted file mode 100644 index a2bce9d..0000000 --- a/C_plus/433_MinimumGeneticMutation.cpp +++ /dev/null @@ -1,42 +0,0 @@ -class Solution -{ -public: - int minMutation(string start, string end, vector &bank) - { - - set banks(bank.begin(), bank.end()); - set visited; - int step = 0; - string b = "ACGT"; - queue q; - visited.insert(start); - q.push(start); - while (!q.empty()) - { - int size = q.size(); - for (int i = 0; i < size; ++i) - { - string p = q.front(); - q.pop(); - if (p == end) - return step; - for (int j = 0; j < 8; ++j) - { - for (char c : b) - { - string temp = p; - temp[j] = c; - if (banks.count(temp) && !visited.count(temp)) - { - q.push(temp); - visited.insert(temp); - } - } - } - } - step++; - } - - return -1; - } -}; \ No newline at end of file diff --git a/C_plus/435*_Non-overlappingIntervals.cpp b/C_plus/435*_Non-overlappingIntervals.cpp deleted file mode 100644 index 6237ea2..0000000 --- a/C_plus/435*_Non-overlappingIntervals.cpp +++ /dev/null @@ -1,47 +0,0 @@ -class Solution -{ -public: - int intervalSchedule(vector > &intervals) - { - // 刪除最少區間能使個區間不重疊 [1,3] [3,5] 不算重疊 - // 總區間個數減去 - 最多有多少個區間不會重叠 - // step1. 將intervals用end升序排列 - // step2. 選擇一個區間x,他結束時間是最早的 - // step3. 把所有與x區間相交的都移除 - // step4. 重複2、3步驟,直到intervals為空。將之前選出的x就是最大不相交子集。 - - if (intervals.size() == 0) - return 0; - - sort(intervals.begin(), intervals.end(), [](vector a, vector b) - { return a[1] < b[1]; }); - - vector ret; - int count = 1; - int x_end = intervals[0][1]; - for (vector interval : intervals) - { - int start = interval[0]; - if (start >= x_end) - { - count++; - x_end = interval[1]; - } - } - return count; - } - int eraseOverlapIntervals(vector > &intervals) - { - // 貪心演算法,每一步都取局部最佳解,最終結果會是全局最佳解。 - // 貪心演算法可以視為動態規劃的一個特例,需滿足更多條件。 - // 暴力法一般需要指數級時間、如果使用動態規劃消除子問題可以達到多項式級別的時間、滿足貪心選擇性質則可以達到線性級別時間 - - // step1. 將intervals用end升序排列 - // step2. 選擇一個區間x,他結束時間是最早的 - // step3. 把所有與x區間相交的都移除 - // step4. 重複2、3步驟,直到intervals為空。將之前選出的x就是最大不相交子集。 - // step5. intervals長度減去最大不相交子集長度即為答案。 - - return intervals.size() - intervalSchedule(intervals); - } -}; \ No newline at end of file diff --git a/C_plus/437*_PathSumIII.cpp b/C_plus/437*_PathSumIII.cpp deleted file mode 100644 index 65bbc6b..0000000 --- a/C_plus/437*_PathSumIII.cpp +++ /dev/null @@ -1,89 +0,0 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution -{ -public: - int countPathsWithSumFromNode(TreeNode *node, int targetSum, int currentSum) - { - if (!node) - return 0; - - currentSum += node->val; - int totalPaths = 0; - if (currentSum == targetSum) - { // Found a path from the root - totalPaths++; - } - - totalPaths += countPathsWithSumFromNode(node->left, targetSum, currentSum); - totalPaths += countPathsWithSumFromNode(node->right, targetSum, currentSum); - return totalPaths; - } - - int pathSum(TreeNode *root, int targetSum) - { - // option1 DFS O(N log N) times - if (!root) - return 0; - - /* Count paths with sum starting from the root. */ - int pathsFromRoot = countPathsWithSumFromNode(root, targetSum, 0); - - /* Try the nodes on the left and right. */ - int pathsOnLeft = pathSum(root->left, targetSum); - int pathsOnRight = pathSum(root->right, targetSum); - return pathsFromRoot + pathsOnLeft + pathsOnRight; - - - // option 2 DFS + hash table O(N) or O(logN) for balanced tree - unordered_map pathCount; - pathCount[0] = 1; - int ret = countPathWitheSum(root, targetSum, 0, pathCount); - - return ret; - } - - int countPathWitheSum(TreeNode *root, int targetSum, int curSum, unordered_map &pathCount) - { - if (!root) - return 0; // Base case - - /* Count paths with sum ending at the the current node */ - curSum += root->val; - int sum = curSum - targetSum; - int totalPaths = 0; - - /* If curSum eaquls targetSum , then one additionl path starts at root. - Add in this path */ - if (pathCount.count(sum)) - totalPaths = pathCount[sum]; - - /* Increment pathCount, recurse, then decrement pathCount. */ - - pathCount[curSum]++; // incrementHashTable(pathCount, curSum, 1); - - totalPaths += countPathWitheSum(root->left, targetSum, curSum, pathCount); - totalPaths += countPathWitheSum(root->right, targetSum, curSum, pathCount); - - pathCount[curSum]--; // incrementHashTable(pathCount, curSum, -1); - return totalPaths; - } - void incrementHashTable(unordered_map &pathCount, int key, int delta) - { - int newCount = pathCount.count(key) ? pathCount[key] : 0; - newCount += delta; - if (newCount == 0) - pathCount.erase(key); - else - pathCount[key] = newCount; - } -}; \ No newline at end of file diff --git a/C_plus/438*_FindAllAnagramsinaString.cpp b/C_plus/438*_FindAllAnagramsinaString.cpp deleted file mode 100644 index 32f5209..0000000 --- a/C_plus/438*_FindAllAnagramsinaString.cpp +++ /dev/null @@ -1,55 +0,0 @@ -class Solution { -public: - vector findAnagrams(string s, string p) { - // option 1 滑動窗口 -// vector ret; -// unordered_map need, window; -// for(char c:p) need[c]++; - -// int left =0, right = 0, valid = 0; -// while(right < s.size()){ -// char c = s[right]; -// right++; -// // update sliding window info. -// if(need.count(c)){ -// window[c]++; -// if(window[c] == need[c]) valid++; -// } - -// while(right - left == p.size()){ - -// // 找到子串p的anagram -// if(valid == need.size() ){ -// ret.push_back(left); -// } - -// char d = s[left]; -// left ++; - -// // update sliding window information -// if(need.count(d)){ - -// if(window[d] == need[d]) valid--; -// window[d]--; -// } -// } -// } -// return ret; - - // option 2 improved sliding window - vector ret; - vector need(26,0), window(26,0); - for(char c:p) need[c-'a']++; - - for(int i=0;i=p.size()) { - window[s[i-p.size()] -'a'] --; - } - if(window == need) ret.push_back(i-p.size()+1); - } - return ret; - - } -}; diff --git a/C_plus/442*_FindAllDuplicatesinanArray.cpp b/C_plus/442*_FindAllDuplicatesinanArray.cpp deleted file mode 100644 index 1d6a36c..0000000 --- a/C_plus/442*_FindAllDuplicatesinanArray.cpp +++ /dev/null @@ -1,37 +0,0 @@ -class Solution -{ -public: - vector findDuplicates(vector &nums) - { - // option 1 O(n) time and O(n) space - // make use of hash table O(logn) - // unordered_map mp; - // vector ret; - // for(int n:nums) mp[n]++; - - // for(auto iter = mp.begin(); iter !=mp.end();++iter){ - - // if(iter->second ==2 ) ret.emplace_back(iter->first); - // } - // return ret; - - // option 2 O(n) time and O(1) space - // use a little bit math - // use set to strot this answer - // abs(arr[i]) -1 原本arr[i]應該被放置的索引位置 , 例如 arr[i] = 4 ,應該放置索引3的位置 - // 依序 scan 陣列,如果先前沒遇到,並將arr[i] = -arr[i] 相反數,有遇過 則為負數則將arr[i]放置set - // - - vector ret; - for (int i = 0; i < nums.size(); ++i) - { - int index = abs(nums[i]) - 1; - - if (nums[index] > 0) - nums[index] = -nums[index]; - else - ret.push_back(abs(nums[i])); - } - return ret; - } -}; \ No newline at end of file diff --git a/C_plus/443*_StringCompression.cpp b/C_plus/443*_StringCompression.cpp deleted file mode 100644 index 7ff5a29..0000000 --- a/C_plus/443*_StringCompression.cpp +++ /dev/null @@ -1,23 +0,0 @@ -class Solution { -public: - int compress(vector& chars) { - // At each iteration, check if the current character is the same as the next character. If not, add its compressed version to the result. - int ret = 0; - string str = ""; - int countConsecutive = 0; - for(int i=0;i=chars.size() || chars[i]!=chars[i+1]){ - if(countConsecutive>1) str += chars[i] + to_string(countConsecutive); - else str += chars[i]; - - countConsecutive = 0; - } - - } - cout<(str.begin(), str.end()); - return str.size(); - } -}; \ No newline at end of file diff --git a/C_plus/445*_AddTwoNumbersII.cpp b/C_plus/445*_AddTwoNumbersII.cpp deleted file mode 100644 index 7c279b5..0000000 --- a/C_plus/445*_AddTwoNumbersII.cpp +++ /dev/null @@ -1,112 +0,0 @@ -/** - * Definition for singly-linked list. - * struct ListNode { - * int val; - * ListNode *next; - * ListNode() : val(0), next(nullptr) {} - * ListNode(int x) : val(x), next(nullptr) {} - * ListNode(int x, ListNode *next) : val(x), next(next) {} - * }; - */ -class Solution -{ -public: - ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) - { - // option 1 - // 1. use stack to store each node - // 2. 按照stack pop順序相加節點至串列 - // 3. reverse linked list - // use stack - // stack s1,s2; - // for(;l1;l1=l1->next) s1.push(l1->val); - // for(;l2;l2=l2->next) s2.push(l2->val); - - // ListNode *ret = new ListNode(0),*p=ret; - // int carry=0, sum; - // while( !s1.empty() || !s2.empty() || carry){ - // sum = carry; - // if(!s1.empty()){ - // sum += s1.top(); - // s1.pop(); - // } - // if(!s2.empty()){ - // sum+= s2.top(); - // s2.pop(); - // } - - // p->next = new ListNode(sum%10); - // p=p->next; - // carry = sum/10; - // } - // // reverse link list - // ListNode *pre =nullptr, *cur = ret->next, *post = ret->next->next; - // while(post){ - // cur->next =pre; - // pre = cur; - // cur=post; - // post=post->next; - // } - // cur->next = pre; - // ret = cur; - // return ret; - - // option 2 use recursive insted of stack - // 1. 先取得各串列長度 - // 2. 對齊 - // 3. 相加 - int len1 = getListLen(l1); - int len2 = getListLen(l2); - - if (len1 >= len2) - return addSecondToFirst(l1, l2, len1, len2); - return addSecondToFirst(l2, l1, len2, len1); - } - int getListLen(ListNode *l) - { - int res = 0; - while (l) - { - res++; - l = l->next; - } - return res; - } - ListNode *addSecondToFirst(ListNode *l1, ListNode *l2, int len1, int len2) - { - ListNode *ret = l1; - while (len1 > len2) - { - l1 = l1->next; - len1--; - } - int carry = addSameWidth(l1, l2); - - carry = addCarryToList(ret, carry, l1); - - if (carry != 0) - { - ret = new ListNode(carry, ret); - } - return ret; - } - int addCarryToList(ListNode *res, int num, ListNode *l1) - { - if (res == l1) - return num; - int carry = addCarryToList(res->next, num, l1); - int sum = carry + res->val; - res->val = sum % 10; - return sum / 10; - } - int addSameWidth(ListNode *l1, ListNode *l2) - { - - if (!l1) - return 0; - int carry = addSameWidth(l1->next, l2->next); - int sum = l1->val + l2->val + carry; - l1->val = sum % 10; - return sum / 10; - } -}; \ No newline at end of file diff --git a/C_plus/448*_FindAllNumbersDisappearedInaArray.cpp b/C_plus/448*_FindAllNumbersDisappearedInaArray.cpp deleted file mode 100644 index da13333..0000000 --- a/C_plus/448*_FindAllNumbersDisappearedInaArray.cpp +++ /dev/null @@ -1,53 +0,0 @@ -class Solution { -public: - vector findDisappearedNumbers(vector& nums) { - // option 1 O(nlogn) - // vector ret; - // sort(nums.begin(), nums.end()); - // vector tmp (nums.size()+1,0); - // for(int i:nums) tmp[i]++; - // for(int i=1;i ret; - for(int i=0;i0) nums[idx] *=-1; - - } - // for(int n:nums) cout<0) ret.push_back(i+1); - } - return ret; - - - - // option 3 O(n) without extra space - // 座標及數值間相互轉換 + 排序 - vector ret; - for(int i=0;ival << ' '; - serialize(root->left, out); - serialize(root->right, out); - - - } - TreeNode* deserialize(istringstream &in) { - string val; - in >> val; - if (val == "#") return nullptr; - TreeNode *root = new TreeNode(stoi(val)); - root->left = deserialize(in); - root->right = deserialize(in); - return root; - } - - // Encodes a tree to a single string. - string serialize(TreeNode* root) { - ostringstream out; - serialize(root, out); - return out.str(); - } - - // Decodes your encoded data to tree. - TreeNode* deserialize(string data) { - istringstream in(data); - return deserialize(in); - - } -}; - -// Your Codec object will be instantiated and called as such: -// Codec* ser = new Codec(); -// Codec* deser = new Codec(); -// string tree = ser->serialize(root); -// TreeNode* ans = deser->deserialize(tree); -// return ans; \ No newline at end of file diff --git a/C_plus/45*_JumpGameII.cpp b/C_plus/45*_JumpGameII.cpp deleted file mode 100644 index bfd1692..0000000 --- a/C_plus/45*_JumpGameII.cpp +++ /dev/null @@ -1,88 +0,0 @@ -class Solution -{ -private: - vector memo; - -public: - int dp(vector &nums, int p) - { - // 定义:从索引 p 跳到最后一格,至少需要 dp(nums, p) 步 - int n = nums.size(); - //base case - if (p >= n - 1) - return 0; - - if (memo[p] != n) - return memo[p]; - - int steps = nums[p]; - // 可以選擇跳 1步 2步 ... - for (int i = 1; i <= steps; ++i) - { - int subProblem = dp(nums, p + i); - memo[p] = min(memo[p], subProblem + 1); - } - return memo[p]; - } - int jump(vector &nums) - { - // option 1 brute force + memo - - // memo initalize - // 2 3 1 1 4 - // 5 5 5 5 5 - // - - // int n = nums.size(); - // memo = vector(n, n); - // return dp(nums, 0); - - // option 2 dp - // 最短步伐可以抵達index-i點 - // 2 3 1 1 4 - // 0 5 5 5 5 - // 0 1 1 5 5 i = 0 dp[j] = min(dp[j], dp[i]+1) - // 0 1 1 2 2 i = 1 - // 0 1 1 2 2 i = 2, i = 3, i = 4 - - // 1 2 1 1 1 - // 0 1 5 5 5 i = 0 - // 0 1 2 2 5 i = 1 - // 0 1 2 2 5 i = 2 - // 0 1 2 2 3 i = 3 - - // int n = nums.size(); - // vector dp(n, n); - // dp[0] = 0; // base case - // for(int i=0;ileft) - node = node->left; - return node; - } - TreeNode *deleteNode(TreeNode *root, int key) - { - if (root == nullptr) - return nullptr; - //先「找」再「改」 - if (root->val == key) - { - //找到了,進行刪除 - // 情況一,刪除點剛好是葉子,刪除則完事 - // 情況二,刪除點有一個孩子,要讓其孩子接替自己位置 - // 情況三,刪除點有兩個孩子,要找左子樹最大節點或是右子樹最小節點來接替自己位置 - // 這兩個 if 把情況 1 和 2 都正確處理了 - if (root->left == nullptr) - return root->right; - if (root->right == nullptr) - return root->left; - - // 處理情況三 - // 找右子樹最小節點 - TreeNode *minNode = getMin(root->right); - // 替代策略 - root->val = minNode->val; - root->right = deleteNode(root->right, minNode->val); - } - else if (root->val > key) - { - // 往左子樹找 - root->left = deleteNode(root->left, key); - } - else if (root->val < key) - { - // 往右子樹找 - root->right = deleteNode(root->right, key); - } - return root; - } -}; \ No newline at end of file diff --git a/C_plus/451_SortCharactersByFrequency.cpp b/C_plus/451_SortCharactersByFrequency.cpp deleted file mode 100644 index a668353..0000000 --- a/C_plus/451_SortCharactersByFrequency.cpp +++ /dev/null @@ -1,41 +0,0 @@ -class Solution -{ -public: - string frequencySort(string s) - { - - // option 1 - // string ret=""; - // priority_queue> q; - // map m; - // for(char c:s) m[c]++; - // for(pair p :m) - // { - // q.push({p.second, p.first}); // logn - // } - // while(!q.empty()){ - // pair p = q.top(); - // q.pop(); - // ret += string(p.first,p.second); //res.append(p.first, p.second); - // } - - // return ret; - - // option 2 - string ret = ""; - map m; - vector v(s.size() + 1); - for (char c : s) - m[c]++; - for (auto a : m) - { - v[a.second].append(a.second, a.first); - } - for (int i = s.size(); i > 0; --i) - { // 因為單詞出現次數不會超過字串長度 - if (!v[i].empty()) - ret.append(v[i]); - } - return ret; - } -}; \ No newline at end of file diff --git a/C_plus/452*_MinimumNumberofArrowstoBurstBalloons.cpp b/C_plus/452*_MinimumNumberofArrowstoBurstBalloons.cpp deleted file mode 100644 index 56c4e3b..0000000 --- a/C_plus/452*_MinimumNumberofArrowstoBurstBalloons.cpp +++ /dev/null @@ -1,37 +0,0 @@ -class Solution -{ -public: - int intervalSchedule(vector > &points) - { - // 最多有多少個區間不會重叠 - if (points.size() == 0) - return 0; - sort(points.begin(), points.end(), [](vector a, vector b) - { - return a[1] point : points) - { - int x_start = point[0]; - if (x_start > x_end) - { - // [1,2],[2,3] 算重疊 - count++; - x_end = point[1]; - } - } - return count; - } - int findMinArrowShots(vector > &points) - { - // 貪心演算法,每一步都取局部最佳解,最終結果會是全局最佳解。 - // 貪心演算法可以視為動態規劃的一個特例,需滿足更多條件。 - // 暴力法一般需要指數級時間、如果使用動態規劃消除子問題可以達到多項式級別的時間、滿足貪心選擇性質則可以達到線性級別時間 - - // 有幾個不重疊區間 - - return intervalSchedule(points); - } -}; \ No newline at end of file diff --git a/C_plus/453*_MinimumMovestoEqualArrayElements.cpp b/C_plus/453*_MinimumMovestoEqualArrayElements.cpp deleted file mode 100644 index 23cb79f..0000000 --- a/C_plus/453*_MinimumMovestoEqualArrayElements.cpp +++ /dev/null @@ -1,23 +0,0 @@ -class Solution -{ -public: - int minMoves(vector &nums) - { - - // 數學問題 - // [1, 2, 3] => 6 + m * 2 = 4 * 3 = > m = 3 - // sum + m次移動* (n-1) 個 = 最終結果 = x 平衡後的數字 * n 個 - - // sum + m * (n-1 ) = n * x - // 6 + m* 2 = 3 * x - // minNum + m = x 帶入原式子 = sum + m(n-1) = n (minNum + m) = nm + n*minNum; - // sum - minNum * n = m - - int mn = INT_MAX, ret = 0; - for (int n : nums) - mn = min(n, mn); - for (int n : nums) - ret += (n - mn); - return ret; - } -}; \ No newline at end of file diff --git a/C_plus/454*_4SumII.cpp b/C_plus/454*_4SumII.cpp deleted file mode 100644 index bc3bb12..0000000 --- a/C_plus/454*_4SumII.cpp +++ /dev/null @@ -1,43 +0,0 @@ -class Solution -{ -public: - int fourSumCount(vector &nums1, vector &nums2, vector &nums3, vector &nums4) - { - // hash table 。存儲AB hash table兩個總和及出現次數,再去找CD hash table找相反數是否存在。 - // O(n^2) - // unordered_map mp; - // for(int i=0;i mp; - int ret = 0; - for (int a : nums1) - { - for (int b : nums2) - { - mp[a + b]++; - } - } - for (int c : nums3) - { - for (int d : nums4) - { - ret += mp[-c - d]; - } - } - return ret; - } -}; \ No newline at end of file diff --git a/C_plus/46*_Permutations.cpp b/C_plus/46*_Permutations.cpp deleted file mode 100644 index 5b56b2d..0000000 --- a/C_plus/46*_Permutations.cpp +++ /dev/null @@ -1,109 +0,0 @@ -class Solution { -public: - void backtrack(vector& nums, vector out, vector> & ret){ - - // backtrack 框架 - // void traverse(TreeNode root) { - // for (TreeNode child : root.childern) - // // 前序遍历需要的操作 - // traverse(child); - // // 后序遍历需要的操作 - // } - - // for 选择 in 选择列表: - // # 做选择 - // 将该选择从选择列表移除 - // 路径.add(选择) - // backtrack(路径, 选择列表) - // # 撤销选择 - // 路径.remove(选择) - // 将该选择再加入选择列表 - - - if(out.size()== nums.size()){ - ret.push_back(out); - return ; - } - for(int i=0 ; i& nums, int start, vector> & ret){ - if(start == nums.size()){ - ret.push_back(nums); - return ; - } - - for(int i=start ;i> permute(vector& nums) { - - // option 1 brute force solution - // vector> ret; - // vector out; - // backtrack(nums, out,ret); - // return ret; - - // option 1.1 brute force solution - swap version - // vector> ret; - // vector out; - // generatePermute(nums, 0,ret); - // return ret; - - - // option 1.2 iterative version - - vector> ret(1); - for(int n:nums){ - int size = ret.size(); - for(int i=0;i temp = ret[i]; - temp.insert( temp.begin()+ j, n); - ret.push_back(temp); - } - ret[i].push_back(n); - } - } - return ret; - // option 1.3 iterative version -// vector> ret(1); -// for(int n:nums){ -// int size = ret.size(); -// for(int i=0;i> ret; - // sort(nums.begin(), nums.end()); - // ret.push_back(nums); - // while(next_permutation(nums.begin(), nums.end())){ - // ret.push_back(nums); - // } - // return ret; - } -}; \ No newline at end of file diff --git a/C_plus/462*_MinimumMovestoEqualArrayElementsII.cpp b/C_plus/462*_MinimumMovestoEqualArrayElementsII.cpp deleted file mode 100644 index 22485e7..0000000 --- a/C_plus/462*_MinimumMovestoEqualArrayElementsII.cpp +++ /dev/null @@ -1,18 +0,0 @@ -class Solution -{ -public: - int minMoves2(vector &nums) - { - - // 排序後 ,取差值 - sort(nums.begin(), nums.end()); - - int i = 0, j = nums.size() - 1; - int ret = 0; - while (i < j) - { - ret += nums[j--] - nums[i++]; - } - return ret; - } -}; \ No newline at end of file diff --git a/C_plus/463_IslandPerimeter.cpp b/C_plus/463_IslandPerimeter.cpp deleted file mode 100644 index 189e65d..0000000 --- a/C_plus/463_IslandPerimeter.cpp +++ /dev/null @@ -1,36 +0,0 @@ -class Solution -{ -public: - int islandPerimeter(vector > &grid) - { - - // 因為是相連所以每個方塊 最多貢獻3 個周長, - // 再去判斷這些方塊 相鄰塊總數 - int m = grid.size(), n = grid[0].size(); - int ret = 0; - for (int i = 0; i < m; ++i) - { - for (int j = 0; j < n; ++j) - { - - if (grid[i][j] == 1) - { - int count = 4; - if (j > 0 && grid[i][j - 1] == 1) - count--; - if (i > 0 && grid[i - 1][j] == 1) - count--; - - if (i < m - 1 && grid[i + 1][j] == 1) - count--; - if (j < n - 1 && grid[i][j + 1] == 1) - count--; - - ret += count; - } - } - } - - return ret; - } -}; \ No newline at end of file diff --git a/C_plus/47*_PermutationsII.cpp b/C_plus/47*_PermutationsII.cpp deleted file mode 100644 index 4c7ba1f..0000000 --- a/C_plus/47*_PermutationsII.cpp +++ /dev/null @@ -1,55 +0,0 @@ -class Solution -{ -public: - void traverse(vector &nums, vector &path, set > &ret, vector &used) - { - - if (nums.size() == path.size()) - { - ret.insert(path); - return; - } - - for (int i = 0; i < nums.size(); ++i) - { - if (used[i]) - continue; - used[i] = true; - path.push_back(nums[i]); - traverse(nums, path, ret, used); - path.pop_back(); - used[i] = false; - } - } - vector > permuteUnique(vector &nums) - { - //option 1 - set> ret; - vector path; - vector used(nums.size(), false); - traverse(nums, path, ret, used); - return vector>(ret.begin(), ret.end()); - - // option 2 - set > res; - permute(nums, 0, res); - return vector >(res.begin(), res.end()); - } - - void permute(vector &nums, int start, set > &ret) - { - - if (start >= nums.size()) - ret.insert(nums); - - for (int i = start; i < nums.size(); ++i) - { - // prune - if (i != start && nums[i] == nums[start]) - continue; - swap(nums[start], nums[i]); - permute(nums, start + 1, ret); - swap(nums[start], nums[i]); - } - } -}; \ No newline at end of file diff --git a/C_plus/475*_Heaters.cpp b/C_plus/475*_Heaters.cpp deleted file mode 100644 index 04c392e..0000000 --- a/C_plus/475*_Heaters.cpp +++ /dev/null @@ -1,28 +0,0 @@ -class Solution { -public: - int findRadius(vector& houses, vector& heaters) { - - int ret = 0; - int n = heaters.size(); - sort(heaters.begin(), heaters.end()); - - for(auto h:houses){ - // binary search - int l =0, r =n; - while(l heaters[mid]) l = mid+1; - else r = mid; - } - cout< &nums) - { - int ret = 0, tmp = 0; - for (int i : nums) - { - if (i == 0) - { - ret = max(ret, tmp); - tmp = 0; - } - else - tmp++; - } - return max(ret, tmp); - } -}; \ No newline at end of file diff --git a/C_plus/48_RotateImage.cpp b/C_plus/48_RotateImage.cpp deleted file mode 100644 index c0646cb..0000000 --- a/C_plus/48_RotateImage.cpp +++ /dev/null @@ -1,41 +0,0 @@ -class Solution -{ -public: - void rotate(vector > &matrix) - { - - // option 1 O(n^2) - // 4點交換 rotate - - if (matrix.size() == 0 || matrix[0].size() == 0) - return; - - int m = matrix.size(); - for (int layer = 0; layer < m / 2; ++layer) - { - int first = layer; - int last = m - 1 - layer; - for (int i = first; i < last; ++i) - { - int offset = i - first; - int top = matrix[first][i]; - matrix[first][i] = matrix[last - offset][first]; - matrix[last - offset][first] = matrix[last][last - offset]; - matrix[last][last - offset] = matrix[i][last]; - matrix[i][last] = top; - } - } - - // optnio 2 O(n^2) - // 1. 以列完單位做reverse - // 2. transpose - - // reverse(matrix.begin(), matrix.end()); - // int m = matrix.size(), n =matrix[0].size(); - // for(int i=0;i > groupAnagrams(vector &strs) - { - vector > ret; - unordered_map m; - - int n = strs.size(); - - for (int i = 0; i < n; ++i) - { - string cand = strs[i]; - sort(cand.begin(), cand.end()); - if (m.count(cand)) - { - int idx = m[cand]; - ret[idx].push_back(strs[i]); - } - else - { - m[cand] = ret.size(); - ret.push_back({}); - ret.back().push_back(strs[i]); - } - } - return ret; - } -}; \ No newline at end of file diff --git a/C_plus/494*_TargetSum.cpp b/C_plus/494*_TargetSum.cpp deleted file mode 100644 index 673e7fb..0000000 --- a/C_plus/494*_TargetSum.cpp +++ /dev/null @@ -1,134 +0,0 @@ -class Solution -{ -public: - void backtrack(vector &nums, int i, int target, int &ret) - { - //base case 結束條件 - if (i == nums.size()) - { - if (target == 0) - ret++; - return; - } - - // 選擇負號 - target += nums[i]; //做選擇 - backtrack(nums, i + 1, target, ret); // 窮舉所有選擇 - target -= nums[i]; // 撤銷選擇 - //backtrack(nums, i+1, target+nums[i], ret); - - // 選擇正號 - target -= nums[i]; //做選擇 - backtrack(nums, i + 1, target, ret); // 窮舉所有選擇 - target += nums[i]; // 撤銷選擇 - //backtrack(nums, i+1, target-nums[i], ret); - } - - int dp(vector &nums, int i, int target, unordered_map &memo) - { - - //base case 結束條件 - if (i == nums.size()) - { - if (target == 0) - return 1; - return 0; - } - - // 轉為字串 - string key = to_string(i) + "," + to_string(target); - - // 用memo避免重複計算 - if (memo.count(key)) - return memo[key]; - - // 選擇正號與服好的排列組合,窮舉 - int result = dp(nums, i + 1, target - nums[i], memo) + - dp(nums, i + 1, target + nums[i], memo); - memo[key] = result; - return result; - } - int findTargetSumWays(vector &nums, int target) - { - // def backtrack(路径, 选择列表): - // if 满足结束条件: - // result.add(路径) - // return - - // for 选择 in 选择列表: - // 做选择 - // backtrack(路径, 选择列表) - // 撤销选择 - // option 1 O(2^N) time - // if(nums.size()==0) return 0; - // int ret =0; - // backtrack(nums, 0, target, ret); - // return ret; - - //option 2 memo 消除重疊子問題 - if (nums.size() == 0) - return 0; - unordered_map memo; - - return dp(nums, 0, target, memo); - - // option 3 - // 將 nums 分成兩個集合 A B分別代表 分配+ - 的個數,那麼 - // sum(A) - sum(B) = target - // sum(A) = target + sum(B) - // sum(A) + sum(A) = target + sum(B) + sum(A) - // 2 * sum(A) = target + sum(nums) - // 將問題變成 nums 中存在幾個子集 A,使得A 中元素的和為 (target + sum(nums))/2 = 4 - // dp 背包問題,容量為 4 ,現在給你 N 個物品,第 i 個物品中 nums[i-1],每個物品只有一個,請問有幾種方法恰好能滿背包 - //sum = 0 1 2 3 4 - // 1 0 0 0 0 - //1 1 1 0 0 0 - //1 1 2 1 0 0 - //1 1 3 3 1 0 - //1 1 4 6 4 1 - //1 1 5 10 10 5 - // 背包問題 通解 if( j >= nums[i-1]) dp[i][j] = dp[i-1][j] + dp[i-1][j - nums[i-1]]; - // 把 第 i-1 物品裝入背包 或不裝入背包的總方法數 - - // int sum =0; - // int n = nums.size(); - // for(int i = 0; i < n; i++) - // sum += nums[i]; - // // 不可能存在合法子集 - // if(sum < target || (sum + target)%2 == 1 ) return 0; - // sum = (sum + target)/2; - - // vector> dp(n+1, vector(sum+1,0)); - // for(int i=0 ;i<=n ;++i) dp[i][0] = 1; - // for(int i = 1;i<=n;++i){ - // for(int j=0;j<=sum ; ++j){ - // if((j >= nums[i-1])) dp[i][j] = dp[i-1][j] + dp[i-1][j - nums[i-1]]; - // else dp[i][j] = dp[i-1][j]; - // } - - // } - // return dp[n][sum]; - - // option 4 reduce dp - int sum = 0; - int n = nums.size(); - for (int i = 0; i < n; i++) - sum += nums[i]; - if (sum < target || (sum + target) % 2 == 1) - return 0; - sum = (sum + target) / 2; - vector dp(sum + 1, 0); - dp[0] = 1; - for (int i = 1; i <= n; ++i) - { - for (int j = sum; j >= 0; j--) - { - // 注意 背包問題化為一維時,要反向搜尋 - if (j >= nums[i - 1]) - dp[j] += dp[j - nums[i - 1]]; - } - } - - return dp[sum]; - } -}; \ No newline at end of file diff --git a/C_plus/496_NextGreaterElementI.cpp b/C_plus/496_NextGreaterElementI.cpp deleted file mode 100644 index 2ad8b17..0000000 --- a/C_plus/496_NextGreaterElementI.cpp +++ /dev/null @@ -1,127 +0,0 @@ -class Solution -{ -public: - vector nextGreaterElement(vector &nums1, vector &nums2) - { - - // option 1 brute force O(n^2) - // vector ret; - // for(int n:nums1){ - // int i=0, next = -1; - // while(nums2[i]!=n) i++; - - // for(i =i+1 ;in){ - // next = nums2[i]; - // break; - // } - // } - // ret.push_back(next); - // } - // return ret; - - // option 2 - // int size = nums2.size(); - // vector dp(size, -1); - - // for(int i=0;inums2[i]){ - // t = nums2[j]; - // break; - // } - // } - // dp[i] = t; - // } - // for(int d:dp) cout< ret; - // for(int n:nums1){ - // int t=-1; - // for(int j=0;j mp; - vector ret; - for (int i = 0; i < nums2.size(); ++i) - mp[nums2[i]] = i; - - for (int n : nums1) - { - - int start = mp[n]; - int t = -1; - for (int j = start + 1; j < nums2.size(); j++) - { - if (nums2[j] > n) - { - t = nums2[j]; - break; - } - } - ret.push_back(t); - } - return ret; - - // option 4 mono stack O(n) 順向 - stack sta; - int size = nums2.size(); - vector mono(size,-1); - - for(int i=0;i nums2[sta.top()]){ - int t = sta.top(); - sta.pop(); - mono[t] = nums2[i]; - } - sta.push(i); - } - - vector ret; - for(int n:nums1){ - auto it = std::find(nums2.begin(), nums2.end(), n ); - int idx = std::distance(nums2.begin(), it); - ret.push_back(mono[idx]); - - } - return ret; - - // option 4 mono stack O(n) 逆向 - // step1. 先對nums2 數列求得下個更大值的數組 - // step2. 在遍歷nums1 用索引找到nums2對應的值, - // 利用該索引找出對應下個更大值的數組的值 - int size = nums2.size(); - // 存放下個更大的數組 - vector ret(size, -1); - stack sta; - for(int i=size-1;i>-1;i--){ - - while(!sta.empty() && sta.top() <= nums2[i]){ - sta.pop(); - } - ret[i] = sta.empty()?-1:sta.top(); - - sta.push(nums2[i]); - } - - vector ans; - for(int n:nums1){ - auto it = find(nums2.begin(),nums2.end() , n); - int idx = std::distance(nums2.begin(), it); - - ans.push_back( ret[idx] ); - - } - - return ans; - } -}; \ No newline at end of file diff --git a/C_plus/4_MedianOfTwoSortedArrays.cpp b/C_plus/4_MedianOfTwoSortedArrays.cpp deleted file mode 100644 index 9fb1e65..0000000 --- a/C_plus/4_MedianOfTwoSortedArrays.cpp +++ /dev/null @@ -1,81 +0,0 @@ -class Solution -{ -public: - double findMedianSortedArrays(vector &nums1, vector &nums2) - { - // option 1 O(n^2) - // 1. use insert sort to merge to one sorted list - // 2. get size/2 index value - int size = nums1.size() + nums2.size(); - vector merge(size, 0); - double ret = 0.0; - for (int i = 0; i < nums1.size(); ++i) - merge[i] = nums1[i]; - for (int i = nums1.size(); i < merge.size(); ++i) - merge[i] = nums2[i - nums1.size()]; - - // sort(merge.begin(), merge.end()); - for (int j = nums1.size(); j < merge.size(); ++j) - { - int key = merge[j]; - int k = j - 1; - while (k > -1 && merge[k] > key) - { - merge[k + 1] = merge[k]; - k--; - } - merge[k + 1] = key; - } - - if (merge.size() % 2 == 1) - { - ret = merge[size / 2]; - } - else - { - ret += merge[size / 2 - 1]; - ret += merge[size / 2]; - ret /= 2; - } - - return ret; - - // option 2 two-pointer O(n logn) - // 1. merge sort to merge two array - // 2. determine merage array length is odd or even , and get median. - // vector merge; - // int l = 0, r = 0; - // while(l= 0 && r < s.size() && s[l] == s[r]) - { - l--; - r++; - } - return s.substr(l + 1, r - l - 1); - } - string longestPalindrome(string s) - { - - // option 1 two point O(n^2) time and O(1) space - // int start = 0, len = 0; - // int n = s.size() ; - // for(int i=0;i0 && r len){ - // start = l; - // len = r-l +1; - // } - // } - - // return s.substr(start , len); - - // option 2 - string ret; - for (int i = 0; i < s.size(); ++i) - { - // 以 s[i] 为中心的最长回文子串 - string s1 = palindrome(s, i, i); - // 以 s[i] 和 s[i+1] 为中心的最长回文子串 - string s2 = palindrome(s, i, i + 1); - - ret = ret.size() > s1.size() ? ret : s1; - ret = ret.size() > s2.size() ? ret : s2; - } - return ret; - } -}; \ No newline at end of file diff --git a/C_plus/501_FindModeinBinarySearchTree.cpp b/C_plus/501_FindModeinBinarySearchTree.cpp deleted file mode 100644 index 663a5d7..0000000 --- a/C_plus/501_FindModeinBinarySearchTree.cpp +++ /dev/null @@ -1,69 +0,0 @@ -/* - * @Author: yuan - * @Date: 2021-07-16 16:14:23 - * @LastEditTime: 2021-07-16 16:19:15 - * @FilePath: /leet_code/C_plus/501_FindModeinBinarySearchTree.cpp - */ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution -{ -public: - void dfs(TreeNode *root, map &mp) - { - if (root == nullptr) - return; - - dfs(root->left, mp); - mp[root->val]++; - dfs(root->right, mp); - } - vector findMode(TreeNode *root) - { - // option 1 O(nlogn) time, O(n) space - // 用hash table紀錄節點的值對應出現頻率 - // map mp; - // dfs(root, mp); - // priority_queue, vector>> pq; - // for(auto p :mp) pq.push(make_pair(p.second, p.first)); - // vector ret; - // int _max =pq.top().first; - // while(!pq.empty()){ - // pair it = pq.top(); - // if(ret.empty() || pq.top().first==_max ) ret.push_back(it.second); - // pq.pop(); - // } - // return ret; - - // option 1.1 improved - map mp; - int _max = 0; - dfs(root, mp, _max); - vector ret; - for (auto m : mp) - { - if (m.second == _max) - ret.push_back(m.first); - } - return ret; - } - void dfs(TreeNode *root, map &mp, int &mx) - { - if (root == nullptr) - return; - - dfs(root->left, mp, mx); - mp[root->val]++; - mx = max(mx, mp[root->val]); - dfs(root->right, mp, mx); - } -}; \ No newline at end of file diff --git a/C_plus/503*_NextGreaterElementII.cpp b/C_plus/503*_NextGreaterElementII.cpp deleted file mode 100644 index a650a1b..0000000 --- a/C_plus/503*_NextGreaterElementII.cpp +++ /dev/null @@ -1,44 +0,0 @@ -class Solution -{ -public: - vector nextGreaterElements(vector &nums) - { - vector ret; - int n = nums.size(); - for (int i = 0; i < n; ++i) - { - int t = -1; - for (int j = i + 1; j < i + n; j++) - { - if (nums[j % n] > nums[i]) - { - t = nums[j % n]; - break; - } - } - ret.push_back(t); - } - return ret; - - - - //option 2 monotonic stack - - int n = nums.size(); - vector ret(n); - stack sta; - // 數組翻倍 - for(int i=2*n -1;i>-1;i--){ - - while(!sta.empty() && sta.top() <= nums[i%n]){ - sta.pop(); - } - - ret[i%n] = sta.empty()?-1:sta.top(); - - sta.push(nums[i%n]); - } - return ret; - - } -}; \ No newline at end of file diff --git a/C_plus/509_FibonacciNumber.cpp b/C_plus/509_FibonacciNumber.cpp deleted file mode 100644 index 8cdb0d6..0000000 --- a/C_plus/509_FibonacciNumber.cpp +++ /dev/null @@ -1,59 +0,0 @@ -class Solution -{ -public: - int helper(vector &memo, int n) - { - //base case - if (n == 0 || n == 1) - return n; - if (memo[n] != 0) - return memo[n]; - memo[n] = helper(memo, n - 1) + helper(memo, n - 2); - return memo[n]; - } - int fib(int n) - { - // 0 1 1 2 3 5 8 13 - - // option 1 brute force solution recusrive O(2^n) time - // if(n==0 || n==1) return n; - // return fib(n-1) + fib(n-2); - - // option 2 memo pattern 備忘錄 O(n) time and O(n) space - // 自頂向下 用 vector 或 hash table 紀錄出現過的避免大量重複運算 - - // vector memo(n+1, 0); - // return helper(memo, n); - - // option 2.1 O(n) time and O(n) space - // dp solution 自底向上 - - // if(n ==0 || n == 1) return n; - // vector dp(n+1,0); - // // base case - // dp[0] = 0; - // dp[1] = 1; - // for(int i=2;i<=n;++i){ - // dp[i] = dp[i-1] + dp[i-2]; - // } - // return dp[n]; - - // option 3 reduce dp - - if (n == 0 || n == 1) - return n; - - int dp_0 = 0, dp_1 = 1; - int ans = 0; - for (int i = 2; i <= n; ++i) - { - ans = dp_0 + dp_1; - - // for next iteration update - dp_0 = dp_1; - dp_1 = ans; - } - - return ans; - } -}; \ No newline at end of file diff --git a/C_plus/50_Pow(x,n).cpp b/C_plus/50_Pow(x,n).cpp deleted file mode 100644 index abe0441..0000000 --- a/C_plus/50_Pow(x,n).cpp +++ /dev/null @@ -1,36 +0,0 @@ -class Solution -{ -public: - double myPow(double x, int n) - { - // brute force - // if(n==0) return 1; - // double ret = 1; - // for (int i = 1; i <= abs(n); i++) { - // // 這裡有乘法,可能overflow - // ret *= x; - // } - // return n<0?1/ret:ret; - - // option 1 recursive - // 如果 n 是偶數,返回myPow(x, n/2)*myPow(x, n/2)即可 - // 如果 n 是奇數,還要注意是否為負數,如果不是負數只要再乘上x即可。 - // 如果 n 是奇數,還要注意是否為負數,如果是負數只要再乘上x的倒數。但可能會溢位,所以延後判斷。 - - // if(n==0) return 1; - // double half = myPow(x, n/2); - // if(n%2==0) return half*half; - // if(n<0) return half*half/x; - // else return half*half*x; - - // option 2 iterative - - // if(n==0) return 1; - // double ret = 1.0; - // for(int i=n;i!=0;i/=2){ - // if(i%2!=0) ret*=x; - // x *=x; - // } - // return n<0?1/ret:ret; - } -}; \ No newline at end of file diff --git a/C_plus/51*_N-Queens.cpp b/C_plus/51*_N-Queens.cpp deleted file mode 100644 index 50e7d18..0000000 --- a/C_plus/51*_N-Queens.cpp +++ /dev/null @@ -1,67 +0,0 @@ -class Solution -{ -public: - void backtrack(vector &board, int row, vector > &ret) - { - // 結束條件 - if (row == board.size()) - { - ret.push_back(board); - return; - } - int n = board[row].size(); - - for (int col = 0; col < n; col++) - { - // 排除不合法選擇 - if (!isValid(board, row, col)) - continue; - // 做選擇 - board[row][col] = 'Q'; - // 進入下一列決策 - backtrack(board, row + 1, ret); - // 撤銷選擇 - board[row][col] = '.'; - } - } - bool isValid(vector &board, int row, int col) - { - - int n = board.size(); - // 檢查是否有皇后衝突 - for (int i = 0; i < n; ++i) - { - if (board[i][col] == 'Q') - return false; - if (board[row][i] == 'Q') - return false; - } - // 檢查右上方是否有其他皇后 - for (int i = row - 1, j = col + 1; - i >= 0 && j < n; - i--, j++) - { - if (board[i][j] == 'Q') - return false; - } - // 檢查左上方是否有其他皇后 - for (int i = row - 1, j = col - 1; - i >= 0 && j >= 0; - i--, j--) - { - if (board[i][j] == 'Q') - return false; - } - return true; - } - vector > solveNQueens(int n) - { - - vector > ret; - - vector board(n, string(n, '.')); - backtrack(board, 0, ret); - - return ret; - } -}; \ No newline at end of file diff --git a/C_plus/513_FindBottomLeftTreeValue.cpp b/C_plus/513_FindBottomLeftTreeValue.cpp deleted file mode 100644 index c8e9a36..0000000 --- a/C_plus/513_FindBottomLeftTreeValue.cpp +++ /dev/null @@ -1,38 +0,0 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution -{ -public: - int findBottomLeftValue(TreeNode *root) - { - // level order traverse - queue q; - q.push(root); - int ret = 0; - while (!q.empty()) - { - int size = q.size(); - ret = q.front()->val; - for (int _ = 0; _ < size; _++) - { - TreeNode *p = q.front(); - q.pop(); - - if (p->left) - q.push(p->left); - if (p->right) - q.push(p->right); - } - } - return ret; - } -}; \ No newline at end of file diff --git a/C_plus/514*_FreedomTrail.cpp b/C_plus/514*_FreedomTrail.cpp deleted file mode 100644 index fe3e010..0000000 --- a/C_plus/514*_FreedomTrail.cpp +++ /dev/null @@ -1,54 +0,0 @@ -class Solution -{ -public: - unordered_map > charToIndex; - vector > memo; - int dp(string &ring, int i, string &key, int j) - { - // 紀錄圓盤指針在ring[i],輸入key[j..] 的最少操作次數 - - // base case,完成輸入 - if (j == key.size()) - return 0; - - // 查看備忘錄 - if (memo[i][j]) - return memo[i][j]; - - int n = ring.size(); - // 做選擇 - int ret = INT_MAX; - - for (int k : charToIndex[key[j]]) - { - // 撥動指針的次數 - int delta = abs(k - i); - // 選擇順時針還是逆時針 - delta = min(delta, n - delta); - // 將指針撥到ring[k],繼續輸入key[j+1..] - int subProblem = dp(ring, k, key, j + 1); - // 選擇整體操作次數最少的 - ret = min(ret, 1 + delta + subProblem); - // PS: 加一 是因為按動按鈕也算一次操作 - } - memo[i][j] = ret; - return ret; - } - int findRotateSteps(string ring, string key) - { - int m = ring.size(); - int n = key.size(); - - memo = vector >(m, vector(n, 0)); - - // 紀錄圓環上字符到索引的映射 - for (int i = 0; i < ring.size(); ++i) - { - charToIndex[ring[i]].push_back(i); - } - - // 圓盤指針最初指向十二點鐘方向 - // 從第一個字符開始輸入 - return dp(ring, 0, key, 0); - } -}; \ No newline at end of file diff --git a/C_plus/515_FindLargestValueinEachTreeRow.cpp b/C_plus/515_FindLargestValueinEachTreeRow.cpp deleted file mode 100644 index 55ffd52..0000000 --- a/C_plus/515_FindLargestValueinEachTreeRow.cpp +++ /dev/null @@ -1,42 +0,0 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution -{ -public: - vector largestValues(TreeNode *root) - { - // level order traverse - if (!root) - return {}; - vector ret; - queue q; - q.push(root); - while (!q.empty()) - { - int size = q.size(); - int temp = q.front()->val; - - for (int i = 0; i < size; ++i) - { - TreeNode *p = q.front(); - q.pop(); - temp = max(temp, p->val); - if (p->left) - q.push(p->left); - if (p->right) - q.push(p->right); - } - ret.push_back(temp); - } - return ret; - } -}; \ No newline at end of file diff --git a/C_plus/516*_LongestPalindromicSubsequence.cpp b/C_plus/516*_LongestPalindromicSubsequence.cpp deleted file mode 100644 index 9232cc5..0000000 --- a/C_plus/516*_LongestPalindromicSubsequence.cpp +++ /dev/null @@ -1,36 +0,0 @@ -class Solution -{ -public: - int longestPalindromeSubseq(string s) - { - // option 1 dp - // if s[i] == s[j] dp[i][j] = 2+ dp[i+1][j-1] - // else dp[i][j] = max(dp[i+1][j], dp[i][j-1]) - // b b b a b - // - // b 1 0 0 0 0 1 2 3 3 4 - // b 0 1 0 0 0 0 1 2 2 3 - // b 0 0 1 0 0 => 0 0 1 1 3 - // a 0 0 0 1 0 0 0 0 1 1 - // b 0 0 0 0 1 0 0 0 0 1 - - int n = s.size(); - vector > dp(n, vector(n, 0)); - - for (int i = 0; i < n; ++i) - dp[i][i] = 1; - - for (int i = n - 1; i >= 0; i--) - { - for (int j = i + 1; j < n; ++j) - { - if (s[i] == s[j]) - dp[i][j] = 2 + dp[i + 1][j - 1]; - else - dp[i][j] = max(dp[i + 1][j], dp[i][j - 1]); - } - } - - return dp[0][n - 1]; - } -}; \ No newline at end of file diff --git a/C_plus/518*_CoinChange2.cpp b/C_plus/518*_CoinChange2.cpp deleted file mode 100644 index 7422460..0000000 --- a/C_plus/518*_CoinChange2.cpp +++ /dev/null @@ -1,70 +0,0 @@ -class Solution -{ -public: - int change(int amount, vector &coins) - { - // 完全背包問題 - // 322. Coin Change - // - // for (int i = 1; i <= n; i++) { - // for (int j = 1; j <= amount; j++) { - // if (j - coins[i-1] >= 0) - // dp[i][j] = dp[i - 1][j] + dp[i][j-coins[i-1]]; - // return dp[N][W] - - // 1 2 5 - // 0 1 2 3 4 5 - // 1 0 0 0 0 0 , initialize - // 1 1 1 1 1 1 , i = 1 , coins[i-1] = 1 - // 1 1 2 2 3 3 , i = 2 coins[i-1] = 2 - // 1 1 2 2 3 4 , i = 3 coins[i-1] = 5 - - int n = coins.size(); - vector > dp(n + 1, vector(amount + 1, 0)); - // base case - for (int i = 0; i <= n; ++i) - dp[i][0] = 1; - - for (int i = 1; i <= n; ++i) - { - for (int j = 1; j <= amount; ++j) - { - if (j - coins[i - 1] >= 0) - dp[i][j] = dp[i - 1][j] + dp[i][j - coins[i - 1]]; - else - dp[i][j] = dp[i - 1][j]; - } - } - return dp[n][amount]; - - // option 2 壓縮dp - // vector dp(amount+1, amount+1); - // dp[0] = 0; - // for(int i= 1;i<=amount ;++i){ - // for(int coin :coins){ - // if(i-coin<0) continue; - // dp[i] = min(dp[i], 1+dp[i-coin]); - // } - // } - - // if (i - coin >= 0) dp[i] = dp[i] + dp[i-coin]; - // 1 2 5 - // 0 1 2 3 4 5 - // 1 0 0 0 0 0 - // - // 1 1 1 1 1 1 , i =0 , coins[i] = 1 - // 1 1 2 2 3 3 , i = 1, coins[i] = 2 - // 1 1 2 2 3 4 , i =2 , coins[i] = 5 - // - - // vector dp(amount+1, 0); - // dp[0] = 1; - // for(int i=0;i=0) dp[j] = dp[j] + dp[j-coins[i]]; - // } - // } - - // return dp[amount]==amount+1?1:dp[amount]; - } -}; \ No newline at end of file diff --git a/C_plus/52*_N-QueensII.cpp b/C_plus/52*_N-QueensII.cpp deleted file mode 100644 index 18410ef..0000000 --- a/C_plus/52*_N-QueensII.cpp +++ /dev/null @@ -1,48 +0,0 @@ -class Solution { -public: - void backtrack(vector & board, int row, int & ret){ - - if(board.size() == row){ - ret++; - return ; - } - - int n= board.size(); - for(int i=0;i & board,int row, int col){ - - int n= board.size(); - for(int i=0;i-1 && j-1&& j>-1;i--, j--){ - if(board[i][j] == 'Q') return false; - } - return true; - - } - int totalNQueens(int n) { - int ret = 0; - vector board(n, string(n, '.')); - backtrack(board, 0, ret); - return ret; - } -}; \ No newline at end of file diff --git a/C_plus/521*_LongestUncommonSubsequenceI.cpp b/C_plus/521*_LongestUncommonSubsequenceI.cpp deleted file mode 100644 index 2081139..0000000 --- a/C_plus/521*_LongestUncommonSubsequenceI.cpp +++ /dev/null @@ -1,15 +0,0 @@ -class Solution -{ -public: - int findLUSlength(string a, string b) - { - - // 情況一,兩字串相等,return -1 - // 情況二,兩字串不相等,return max(n,m) - int n = a.size(), m = b.size(); - if (a == b) - return -1; - else - return max(n, m); - } -}; \ No newline at end of file diff --git a/C_plus/522*_LongestUncommonSubsequenceII.cpp b/C_plus/522*_LongestUncommonSubsequenceII.cpp deleted file mode 100644 index dbd69de..0000000 --- a/C_plus/522*_LongestUncommonSubsequenceII.cpp +++ /dev/null @@ -1,36 +0,0 @@ -class Solution -{ -public: - bool checkSubs(string a, string b) - { - int i = 0; - - for (char c : b) - { - if (c == a[i]) - ++i; - if (i == a.size()) - break; - } - return i == a.size(); - } - int findLUSlength(vector &strs) - { - int n = strs.size(); - int ret = -1; - int j = 0; - for (int i = 0; i < n; ++i) - { - for (j = 0; j < n; ++j) - { - if (i == j) - continue; - if (checkSubs(strs[i], strs[j])) - break; - } - if (j == n) - ret = max(ret, (int)strs[i].size()); - } - return ret; - } -}; \ No newline at end of file diff --git a/C_plus/525*_ContiguousArray.cpp b/C_plus/525*_ContiguousArray.cpp deleted file mode 100644 index 5902165..0000000 --- a/C_plus/525*_ContiguousArray.cpp +++ /dev/null @@ -1,21 +0,0 @@ -class Solution -{ -public: - int findMaxLength(vector &nums) - { - map m{{0, -1}}; // use map to record sum-start pt mapping - int ret, sum = 0; // 遇一加一,遇零減一 - for (int i = 0; i < nums.size(); ++i) - { - sum += nums[i] == 1 ? 1 : -1; - if (m.count(sum)) - { - // cout< &nums) - { - // option 0 brute - // int ret = nums[0]; - // for(int i=0;i dp(nums.begin(), nums.end()); // initalize dp - // for(int i=1;i global_max) - // { - // global_max = local_max; - // } - // } - // return global_max; - } - int GetMax(vector &nums, int l, int r) - { - - if (l >= r) - return nums[l]; - int mid = (l + r) / 2; - int lmax = GetMax(nums, l, mid - 1); - int rmax = GetMax(nums, mid + 1, r); - int mmax = nums[mid]; - int temp = nums[mid]; - for (int i = mid - 1; i >= l; i--) - { - - temp += nums[i]; - mmax = max(mmax, temp); - } - - temp = mmax; - for (int i = mid + 1; i <= r; ++i) - { - - temp += nums[i]; - mmax = max(mmax, temp); - } - return max(mmax, max(lmax, rmax)); - } -}; diff --git a/C_plus/530_MinimumAbsoluteDifferenceinBST.cpp b/C_plus/530_MinimumAbsoluteDifferenceinBST.cpp deleted file mode 100644 index edba80b..0000000 --- a/C_plus/530_MinimumAbsoluteDifferenceinBST.cpp +++ /dev/null @@ -1,43 +0,0 @@ -/* - * @Author: yuan - * @Date: 2021-07-16 16:27:03 - * @LastEditTime: 2021-07-16 16:27:03 - * @FilePath: /leet_code/C_plus/530_MinimumAbsoluteDifferenceinBST.cpp - */ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution -{ -public: - void preorder(TreeNode *root, vector &vec) - { - if (root == nullptr) - return; - preorder(root->left, vec); - vec.push_back(root->val); - preorder(root->right, vec); - } - int getMinimumDifference(TreeNode *root) - { - // option 1 用dfs + preorder 紀錄節點 - - vector vec; - int ret = 100001; - preorder(root, vec); - for (int i = 1; i < vec.size(); ++i) - { - int diff = abs(vec[i] - vec[i - 1]); - ret = min(diff, ret); - } - return ret; - } -}; \ No newline at end of file diff --git a/C_plus/537*_ComplexNumberMultiplication.cpp b/C_plus/537*_ComplexNumberMultiplication.cpp deleted file mode 100644 index ca75c72..0000000 --- a/C_plus/537*_ComplexNumberMultiplication.cpp +++ /dev/null @@ -1,14 +0,0 @@ -class Solution -{ -public: - string complexNumberMultiply(string num1, string num2) - { - int n1 = num1.size(), n2 = num2.size(); - auto p1 = num1.find_last_of("+"), p2 = num2.find_last_of("+"); - int a1 = stoi(num1.substr(0, p1)), b1 = stoi(num2.substr(0, p2)); - int a2 = stoi(num1.substr(p1 + 1, n1 - p1 - 2)); - int b2 = stoi(num2.substr(p2 + 1, n2 - p2 - 2)); - int r1 = a1 * b1 - a2 * b2, r2 = a1 * b2 + a2 * b1; - return to_string(r1) + "+" + to_string(r2) + "i"; - } -}; \ No newline at end of file diff --git a/C_plus/540_SingleElementinaSortedArray.cpp b/C_plus/540_SingleElementinaSortedArray.cpp deleted file mode 100644 index c617d03..0000000 --- a/C_plus/540_SingleElementinaSortedArray.cpp +++ /dev/null @@ -1,46 +0,0 @@ -class Solution -{ -public: - int singleNonDuplicate(vector &nums) - { - // option 1 - // O(n) time O(1) space - // if(nums.size()==1) return nums[0]; - // int ret = 0; - // for(int i =0;i > updateMatrix(vector > &mat) - { - - // option 1 BFS - int n = mat.size(), m = mat[0].size(); - vector > ret = mat; - queue > q; - for (int i = 0; i < n; ++i) - { - for (int j = 0; j < m; ++j) - { - if (ret[i][j] == 0) - q.push({i, j}); - else - ret[i][j] = -1; - } - } - - vector > dirs{{0, -1}, {-1, 0}, {0, 1}, {1, 0}}; - while (!q.empty()) - { - auto t = q.front(); - q.pop(); - cout << t.first << " " << t.second << endl; - for (auto dir : dirs) - { - int x = t.first + dir[0], y = t.second + dir[1]; - if (x < 0 || x > n - 1 || y < 0 || y > m - 1 || ret[x][y] != -1) - continue; - ret[x][y] = 1 + ret[t.first][t.second]; - - q.push({x, y}); - } - } - - return ret; - - // option 2 dp + two scan - } -}; \ No newline at end of file diff --git a/C_plus/543*_DiameterOfBinaryTree.cpp b/C_plus/543*_DiameterOfBinaryTree.cpp deleted file mode 100644 index 5aa93cd..0000000 --- a/C_plus/543*_DiameterOfBinaryTree.cpp +++ /dev/null @@ -1,30 +0,0 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution -{ -public: - int depth(TreeNode *root, int &ret) - { - if (!root) - return 0; - int left = depth(root->left, ret); - int right = depth(root->right, ret); - ret = max(ret, left + right); - return 1 + max(left, right); - } - int diameterOfBinaryTree(TreeNode *root) - { - int ret = 0; - depth(root, ret); - return ret; - } -}; \ No newline at end of file diff --git a/C_plus/547*_NumberofProvinces.cpp b/C_plus/547*_NumberofProvinces.cpp deleted file mode 100644 index 761268c..0000000 --- a/C_plus/547*_NumberofProvinces.cpp +++ /dev/null @@ -1,81 +0,0 @@ -class UF -{ -private: - vector parent, size; - -public: - UF(int n) - { - size = vector(n); - parent = vector(n); - for (int i = 0; i < n; ++i) - { - size[i] = 1; - parent[i] = i; - } - } - bool connect(int p, int q) - { - int pRoot = find(p); - int qRoot = find(q); - return pRoot == qRoot; - } - void unionSet(int p, int q) - { - int pRoot = find(p); - int qRoot = find(q); - if (pRoot == qRoot) - return; - - if (size[pRoot] > size[qRoot]) - { - parent[qRoot] = pRoot; - size[pRoot] += size[qRoot]; - } - else - { - parent[pRoot] = qRoot; - size[qRoot] += size[pRoot]; - } - } - int count() - { - // Count parent[x] = x - int count = 0; - for (int i = 0; i < parent.size(); ++i) - { - if (parent[i] == i) - count++; - } - return count; - } - int find(int x) - { - while (x != parent[x]) - { - x = parent[x]; - } - return x; - } -}; -class Solution -{ -public: - int findCircleNum(vector > &isConnected) - { - - int n = isConnected.size(); - UF uf = UF(n); - for (int i = 0; i < n; ++i) - { - for (int j = 0; j < n; ++j) - { - if (j == i) - continue; - if (isConnected[i][j] == 1) - uf.unionSet(i, j); - } - } - return uf.count(); - } -}; \ No newline at end of file diff --git a/C_plus/54_SpiralMatrix.cpp b/C_plus/54_SpiralMatrix.cpp deleted file mode 100644 index 67ea92d..0000000 --- a/C_plus/54_SpiralMatrix.cpp +++ /dev/null @@ -1,38 +0,0 @@ -class Solution -{ -public: - vector spiralOrder(vector > &matrix) - { - int n = matrix.size(), m = matrix[0].size(); - vector paths; - vector > used(n, vector(m, false)); - vector acts = {0, 1, 0, -1}; - // {0,1} {1,0} {0,-1} {-1,0} - int p = n * m, a = 0; - int i = 0, j = -1; - int pre_x = 0, pre_y = 0; - int x = 0, y = 0; - while (p) - { - x = i + acts[a % 4], y = j + acts[(a + 1) % 4]; - // cout< n - 1 || y > m - 1 || x < 0 || y < 0 || used[x][y] == true) - { - a++; - x = i + acts[a % 4]; - y = j + acts[(a + 1) % 4]; - // cout<<"the corner\t, reannge:\t"<l && s[r]==' ') r--; - string ret; - - for(int i=l;i<=r;++i){ - if(s[i]==' '){ - string temp = s.substr(l, i-l); - while(s[i]==' ') i++; - reverse(temp.begin(), temp.end()); - ret+= temp + ' '; - l=i; - } - } - string temp = s.substr(l, r+1-l); - reverse(temp.begin(), temp.end()); - ret += temp; - return ret; - } -}; \ No newline at end of file diff --git a/C_plus/559*_MaximumDepthofN-aryTree.cpp b/C_plus/559*_MaximumDepthofN-aryTree.cpp deleted file mode 100644 index 832e2d0..0000000 --- a/C_plus/559*_MaximumDepthofN-aryTree.cpp +++ /dev/null @@ -1,41 +0,0 @@ -/* - * @Author: yuan - * @Date: 2021-07-16 19:42:54 - * @LastEditTime: 2021-07-16 19:42:54 - * @FilePath: /leet_code/C_plus/559*_MaximumDepthofN-aryTree.cpp - */ -/* -// Definition for a Node. -class Node { -public: - int val; - vector children; - - Node() {} - - Node(int _val) { - val = _val; - } - - Node(int _val, vector _children) { - val = _val; - children = _children; - } -}; -*/ - -class Solution -{ -public: - int maxDepth(Node *root) - { - if (!root) - return 0; - int ret = 1; - for (Node *x : root->children) - { - ret = max(1 + maxDepth(x), ret); - } - return ret; - } -}; \ No newline at end of file diff --git a/C_plus/55_JumpGame.cpp b/C_plus/55_JumpGame.cpp deleted file mode 100644 index 8bc5533..0000000 --- a/C_plus/55_JumpGame.cpp +++ /dev/null @@ -1,64 +0,0 @@ -class Solution -{ -public: - bool canJump(vector &nums) - { - // option 0 time out - // 2 3 1 1 4 - // f t t - // f t t t t - - // int n = nums.size(); - // vector dp(n,false) ; - // dp[0] = true; - // for(int i=0;i dp(n,0); - // for(int i=1;i= n - 1 ? true : false; - } -}; \ No newline at end of file diff --git a/C_plus/560*_SubarraySumEqualsK.cpp b/C_plus/560*_SubarraySumEqualsK.cpp deleted file mode 100644 index 9255eda..0000000 --- a/C_plus/560*_SubarraySumEqualsK.cpp +++ /dev/null @@ -1,53 +0,0 @@ -class Solution -{ -public: - int subarraySum(vector &nums, int k) - { - // option 1 brute O(n^2) time out - - // int sum = 0, n=nums.size(), ret=0; - // for(int i=0;i sum =nums; - // for(int i=1;i=0;j--){ - // if(sum[i]-sum[j] ==k) ret++; - // } - // } - - // return ret; - - // option 3 O(n) time and O(n) space - // 前綴和主要適用場景是原始數組不會步修改的情況下,頻繁的查詢某個區間的累加和。 - int n = nums.size(); - vector sum = vector(n+1,0); - for(int i=1;i<=n;++i) sum[i] = sum[i-1] + nums[i-1]; - unordered_map mp; - //base case - mp[0] = 1; - int ret = 0; - for(int i=1;i<=n ;++i){ - int target = sum[i] - k; - if(mp.count(target)){ - ret += mp[target]; - } - mp[sum[i]]++; - } - return ret; - - } -}; \ No newline at end of file diff --git a/C_plus/563*_BinaryTreeTilt.cpp b/C_plus/563*_BinaryTreeTilt.cpp deleted file mode 100644 index 38052b5..0000000 --- a/C_plus/563*_BinaryTreeTilt.cpp +++ /dev/null @@ -1,40 +0,0 @@ -/* - * @Author: yuan - * @Date: 2021-07-16 17:26:22 - * @LastEditTime: 2021-07-16 17:26:22 - * @FilePath: /leet_code/C_plus/563*_BinaryTreeTilt.cpp - */ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution -{ -public: - int Tilt(TreeNode *root, int &sum) - { - if (!root) - return 0; - - int leftSum = Tilt(root->left, sum); - int rightSum = Tilt(root->right, sum); - sum += abs(leftSum - rightSum); - return leftSum + rightSum + root->val; - } - int findTilt(TreeNode *root) - { - // postorder - if (!root) - return 0; - int ret = 0; - Tilt(root, ret); - return ret; - } -}; \ No newline at end of file diff --git a/C_plus/565_ArrayNesting.cpp b/C_plus/565_ArrayNesting.cpp deleted file mode 100644 index 67a4bdf..0000000 --- a/C_plus/565_ArrayNesting.cpp +++ /dev/null @@ -1,24 +0,0 @@ -class Solution -{ -public: - int arrayNesting(vector &nums) - { - // option 1 O(n) time and O(n) space - int n = nums.size(); - vector visited(n, false); - int ret = 0; - for (int i = 0; i < n; ++i) - { - int j = i; - int cand = 0; - while (visited[j] == false) - { - cand++; - visited[j] = true; - j = nums[j]; - } - ret = max(ret, cand); - } - return ret; - } -}; \ No newline at end of file diff --git a/C_plus/566*_ReshapetheMatrix.cpp b/C_plus/566*_ReshapetheMatrix.cpp deleted file mode 100644 index ae8190d..0000000 --- a/C_plus/566*_ReshapetheMatrix.cpp +++ /dev/null @@ -1,37 +0,0 @@ -class Solution -{ -public: - vector > matrixReshape(vector > &mat, int r, int c) - { - int m = mat.size(), n = mat[0].size(); - if (m * n != r * c) - return mat; - vector > ret(r, vector(c, 0)); - for (int i = 0; i < r; ++i) - { - for (int j = 0; j < c; ++j) - { - int k = i * c + j; - ret[i][j] = mat[k / n][k % n]; - } - } - return ret; - - - // option 2 - vector> ret(r, vector(c,0)); - int n = mat.size(), m = mat[0].size(); - if(m*n !=r*c) return mat; - int k = 0, l =0; - for(int i =0;i need, window; - // for(char c:s1) need[c]++; - // int left = 0, right = 0, valid = 0; - - // while(right < s2.size()){ - - // char c = s2[right]; - // right++; - - // // 更新窗口內數據 - // if(need.count(c)){ - // window[c]++; - // if(window[c] == need[c]) valid++; - // } - - // //判斷窗口左側是否要收縮 - // while(right - left == s1.size()){ - - // // 找到合法子字串 - // if (valid == need.size()) return true; - - // char d = s2[left]; - // left++; - // // 更新窗口內數據 - // if(need.count(d)){ - // if(window[d] == need[d]) valid--; - // window[d]--; - // } - - // } - - // } - // return false; - - // option 2 簡化移動窗口 及 option 2 O(n) - vector window(26, 0); - vector need(26, 0); - for (char c : s1) - need[c - 'a']++; - for (int i = 0; i < s2.size(); ++i) - { - window[s2[i] - 'a']++; - if (i >= s1.size()) - window[s2[i - s1.size()] - 'a']--; - // 因為重新排列後長度一樣 - if (window == need) - return true; - } - return false; - } -}; \ No newline at end of file diff --git a/C_plus/56_MergeIntervals.cpp b/C_plus/56_MergeIntervals.cpp deleted file mode 100644 index 26c1e50..0000000 --- a/C_plus/56_MergeIntervals.cpp +++ /dev/null @@ -1,68 +0,0 @@ -class Solution -{ -public: - vector > merge(vector > &intervals) - { - - sort(intervals.begin(), intervals.end(), [](vector &a, vector &b) - { - if (a[0] == b[0]) - return a[1] > b[1]; //終點降序排序 - return a[0] < b[0]; // 起點做升序排序 - }); - - vector > ret; - int n = intervals.size(); - ret.push_back(intervals[0]); - for (int i = 1; i < n; ++i) - { - vector cur = intervals[i]; - if (ret.back()[1] >= cur[1]) - { - continue; - } - else if (ret.back()[1] >= cur[0] && ret.back()[1] <= cur[1]) - { - ret.back()[1] = cur[1]; - } - else if (ret.back()[1] < cur[0]) - { - ret.push_back(cur); - } - } - - // option 2 - // for(int i=1;i cur = intervals[i]; - // if(cur[0] <= ret.back()[1]){ - // // overlap - // ret.back()[0] = min(ret.back()[0], cur[0]); - // ret.back()[1] = max(ret.back()[1], cur[1]); - // } - // else{ - // ret.push_back({cur[0], cur[1]}); - // } - // } - // option 2.1 - - vector > ret; - sort(intervals.begin(), intervals.end()); - - ret.push_back({intervals[0][0], intervals[0][1]}); - for (int i = 1; i < intervals.size(); ++i) - { - vector cur = intervals[i]; - if (cur[0] <= ret.back()[1]) - { - ret.back()[1] = max(cur[1], ret.back()[1]); - } - else - { - ret.push_back({cur[0], cur[1]}); - } - } - - return ret; - return ret; - } -}; \ No newline at end of file diff --git a/C_plus/572*_SubtreeofAnotherTree.cpp b/C_plus/572*_SubtreeofAnotherTree.cpp deleted file mode 100644 index 6a55181..0000000 --- a/C_plus/572*_SubtreeofAnotherTree.cpp +++ /dev/null @@ -1,60 +0,0 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution -{ -public: - bool isSameTree(TreeNode *p, TreeNode *q) - { - if (p == nullptr && q == nullptr) - return true; - else if (!p || !q) - return false; - else if (p->val == q->val) - return isSameTree(p->left, q->left) && isSameTree(p->right, q->right); - return false; // p->val !=q->val - } - bool isSubtree(TreeNode *root, TreeNode *subRoot) - { - // option 1 - // if (!root) return false; - // if (isSameTree(root, subRoot)) return true; - // return isSubtree(root->left, subRoot) || isSubtree(root->right, subRoot); - - // option 1.1 is equal to option 1 - // O(n + m) time and O(log(n) + log(m)) space - // if(subRoot==nullptr) return true; - // if(root==nullptr) return false; - // else if(root->val ==subRoot->val && isSameTree(root, subRoot)) return true; - // return isSubtree(root->left, subRoot) || isSubtree(root->right, subRoot); - - // option 2 - // 將每個葉子的left child 補上 "#" - string str1, str2; - serialize(root, str1); - serialize(subRoot, str2); - cout << str1 << endl - << str2 << endl; - return str1.find(str2) != string::npos; - } - void serialize(TreeNode *node, string &str) - { - if (node == nullptr) - { - str.append("X"); - return; - } - //in-order traverse - str.append("," + to_string(node->val)); //avoid [12] [2] - serialize(node->left, str); - serialize(node->right, str); - } -}; diff --git a/C_plus/57_InsertInterval.cpp b/C_plus/57_InsertInterval.cpp deleted file mode 100644 index 136bd88..0000000 --- a/C_plus/57_InsertInterval.cpp +++ /dev/null @@ -1,38 +0,0 @@ -class Solution -{ -public: - vector > insert(vector > &intervals, vector &newInterval) - { - - intervals.push_back(newInterval); - // sort(intervals.begin(), intervals.end(), [](vector &a, vector& b){ - // return a[1]>b[1]; - - // }); - sort(intervals.begin(), intervals.end()); - vector > ret; - ret.push_back(intervals[0]); - // [1,3] [2,5] = [1,5] - // [1,8] [2,5] - // [1,5] [7,10] - - for (int i = 1; i < intervals.size(); ++i) - { - vector cur = intervals[i]; - if (ret.back()[1] >= cur[0] && ret.back()[1] <= cur[1]) - { - // case 1 - ret.back() = {ret.back()[0], cur[1]}; - } - else if (ret.back()[1] >= cur[0] && ret.back()[1] > cur[1]) - { - continue; - } - else - { - ret.push_back(cur); - } - } - return ret; - } -}; \ No newline at end of file diff --git a/C_plus/583*_DeleteOperationforTwoStrings.cpp b/C_plus/583*_DeleteOperationforTwoStrings.cpp deleted file mode 100644 index 8e666e6..0000000 --- a/C_plus/583*_DeleteOperationforTwoStrings.cpp +++ /dev/null @@ -1,74 +0,0 @@ -class Solution -{ -public: - map, int> memo; - int distance(string s1, string s2, int i, int j) - { - if (i == -1) - return j + 1; - if (j == -1) - return i + 1; - - if (memo.count(make_pair(i, j))) - return memo[make_pair(i, j)]; - - if (s1[i] == s2[j]) - memo[make_pair(i, j)] = distance(s1, s2, i - 1, j - 1); - else - memo[make_pair(i, j)] = min( - distance(s1, s2, i - 1, j) + 1, - distance(s1, s2, i, j - 1) + 1); - return memo[make_pair(i, j)]; - } - //1143. Longest Common Subsequence - int longestCommonSubsequence(string text1, string text2) - { - int n = text1.size(), m = text2.size(); - vector > dp(n + 1, vector(m + 1, 0)); - - for (int i = 1; i <= n; ++i) - { - for (int j = 1; j <= m; ++j) - { - if (text1[i - 1] == text2[j - 1]) - dp[i][j] = dp[i - 1][j - 1] + 1; - else - dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]); - } - } - return dp[n][m]; - } - int minDistance(string word1, string word2) - { - // come from leetcode 72. Edit Distance - // option 1 - return distance(word1, word2, word1.size() - 1, word2.size() - 1); - - // option 2 dp - int n = word1.size(), m = word2.size(); - vector > dp(n + 1, vector(m + 1, 0)); - for (int i = 0; i <= n; ++i) - dp[i][0] = i; - for (int j = 0; j <= m; ++j) - dp[0][j] = j; - - for (int i = 1; i <= n; ++i) - { - for (int j = 1; j <= m; ++j) - { - if (word1[i - 1] == word2[j - 1]) - dp[i][j] = dp[i - 1][j - 1]; - else - dp[i][j] = min(dp[i - 1][j], dp[i][j - 1]) + 1; - } - } - return dp[n][m]; - - // 相等於 需要刪除多少字符才會變相同 - // 刪除多少字符 也等於 可由求最長公共子序列得知 - - int n = word1.size(), m = word2.size(); - int lcs = longestCommonSubsequence(word1, word2); - return m - lcs + n - lcs; - } -}; \ No newline at end of file diff --git a/C_plus/589_N-aryTreePreorderTraversal.cpp b/C_plus/589_N-aryTreePreorderTraversal.cpp deleted file mode 100644 index 0157051..0000000 --- a/C_plus/589_N-aryTreePreorderTraversal.cpp +++ /dev/null @@ -1,49 +0,0 @@ -/* - * @Author: yuan - * @Date: 2021-07-16 20:07:53 - * @LastEditTime: 2021-07-16 20:09:49 - * @FilePath: /leet_code/C_plus/589_N-aryTreePreorderTraversal.cpp - */ -/* -// Definition for a Node. -class Node { -public: - int val; - vector children; - - Node() {} - - Node(int _val) { - val = _val; - } - - Node(int _val, vector _children) { - val = _val; - children = _children; - } -}; -*/ - -class Solution -{ -public: - void preorder(Node *root, vector &ret) - { - if (!root) - return; - - ret.push_back(root->val); - - for (Node *child : root->children) - { - // left to right - preorder(child, ret); - } - } - vector preorder(Node *root) - { - vector ret; - preorder(root, ret); - return ret; - } -}; \ No newline at end of file diff --git a/C_plus/58_LengthOfLastWord.cpp b/C_plus/58_LengthOfLastWord.cpp deleted file mode 100644 index df75df5..0000000 --- a/C_plus/58_LengthOfLastWord.cpp +++ /dev/null @@ -1,32 +0,0 @@ -class Solution -{ -public: - int lengthOfLastWord(string s) - { - int ret = 0; - int r = s.size() - 1; - while (s[r] == ' ' && r > 0) - r--; - int l = 0; - for (l = 0; l <= r; ++l) - { - ret++; - if (s[l] == ' ') - ret = 0; - } - return ret; - - // option 2 - int l = -1, r = s.size() - 1; - while (r > l && s[r] == ' ') - r--; - for (int i = 0; i <= r; ++i) - { - if (s[i] == ' ') - l = i; - } - if (l == -1) - return r + 1; - return r - l; - } -}; \ No newline at end of file diff --git a/C_plus/590_N-aryTreePostorderTraversal.cpp b/C_plus/590_N-aryTreePostorderTraversal.cpp deleted file mode 100644 index 1164423..0000000 --- a/C_plus/590_N-aryTreePostorderTraversal.cpp +++ /dev/null @@ -1,47 +0,0 @@ -/* - * @Author: yuan - * @Date: 2021-07-16 20:13:25 - * @LastEditTime: 2021-07-16 20:13:25 - * @FilePath: /leet_code/C_plus/590_N-aryTreePostorderTraversal.cpp - */ -/* -// Definition for a Node. -class Node { -public: - int val; - vector children; - - Node() {} - - Node(int _val) { - val = _val; - } - - Node(int _val, vector _children) { - val = _val; - children = _children; - } -}; -*/ - -class Solution -{ -public: - void postorder(Node *root, vector &ret) - { - - if (!root) - return; - for (Node *child : root->children) - { - postorder(child, ret); - } - ret.push_back(root->val); - } - vector postorder(Node *root) - { - vector ret; - postorder(root, ret); - return ret; - } -}; \ No newline at end of file diff --git a/C_plus/598_RangeAdditionII.cpp b/C_plus/598_RangeAdditionII.cpp deleted file mode 100644 index 962a9ef..0000000 --- a/C_plus/598_RangeAdditionII.cpp +++ /dev/null @@ -1,18 +0,0 @@ -class Solution -{ -public: - int maxCount(int m, int n, vector > &ops) - { - - // option 1 - if (ops.empty()) - return m * n; - int a = m, b = n; - for (vector op : ops) - { - a = min(op[0], a); - b = min(op[1], b); - } - return a * b; - } -}; \ No newline at end of file diff --git a/C_plus/59_SpiralMatrixII.cpp b/C_plus/59_SpiralMatrixII.cpp deleted file mode 100644 index faa2fee..0000000 --- a/C_plus/59_SpiralMatrixII.cpp +++ /dev/null @@ -1,28 +0,0 @@ -class Solution -{ -public: - vector > generateMatrix(int n) - { - vector acts = {0, 1, 0, -1}; - vector > ret(n, vector(n, 0)); - vector > used(n, vector(n, false)); - int i = 0, j = -1, a = 0, p = 1; - while (p <= n * n) - { - int x = i + acts[a % 4]; - int y = j + acts[(a + 1) % 4]; - - while (x < 0 || x > n - 1 || y > n - 1 || y < 0 || used[x][y]) - { - a++; - x = i + acts[a % 4]; - y = j + acts[(a + 1) % 4]; - } - ret[x][y] = p++; - used[x][y] = true; - i = x; - j = y; - } - return ret; - } -}; \ No newline at end of file diff --git a/C_plus/6*_ZigZagConversion.cpp b/C_plus/6*_ZigZagConversion.cpp deleted file mode 100644 index 34b3d1d..0000000 --- a/C_plus/6*_ZigZagConversion.cpp +++ /dev/null @@ -1,28 +0,0 @@ -class Solution -{ -public: - string convert(string s, int numRows) - { - if (numRows == 1) - return s; - vector ret(numRows); - int n = s.size(); - int period = numRows * 2 - 2; - for (int i = 0; i < n; ++i) - { - int mod = i % period; - if (mod < numRows) - { - ret[mod] += s[i]; - } - else - { - ret[period - mod] += s[i]; - } - } - string str; - for (string s : ret) - str += s; - return str; - } -}; \ No newline at end of file diff --git a/C_plus/60*_PermutationSequence.cpp b/C_plus/60*_PermutationSequence.cpp deleted file mode 100644 index a3e8d0b..0000000 --- a/C_plus/60*_PermutationSequence.cpp +++ /dev/null @@ -1,76 +0,0 @@ -class Solution -{ -public: - vector nextPermutation(vector nums) - { - // 1 2 7 4 3 1 - // 1 3 7 4 2 1 - // 1. 從右往左找第一個非遞增數字 - // 2. 找到2 索引i 之後,從右往左找第一個比2大的數字索引j - // 3. swap(s[i], s[j]) - // 4. reverse(s.begin() + i+1, s.end()) - - int n = nums.size(); - int i, j; - for (i = n - 2; i > -1; i--) - { - if (nums[i] < nums[i + 1]) - break; - } - if (i < 0) - reverse(nums.begin(), nums.end()); - else - { - for (j = n - 1; j > i; j--) - { - if (nums[j] > nums[i]) - break; - } - - swap(nums[i], nums[j]); - reverse(nums.begin() + i + 1, nums.end()); - } - - return nums; - } - - void traverse(string s, int k, string out, vector &ret) - { - if (out.size() == s.size()) - { - ret.push_back(out); - return; - } - - for (int i = 0; i < s.size(); ++i) - { - if (out.find(s[i]) != string::npos) - continue; - out = out + s[i]; - traverse(s, i + 1, out, ret); - out.pop_back(); - } - } - string getPermutation(int n, int k) - { - - // option 1 O(n) time out - // generate string depend n - // vector next(n); - // for(int i=1;i<=n;++i) next[i-1] = i; - // string ret ; - // for(int i=1;i ret; - traverse(s, 0, "", ret); - return ret[k - 1]; - } -}; \ No newline at end of file diff --git a/C_plus/600*_Non-negativeIntegerswithoutConsecutiveOnes.cpp b/C_plus/600*_Non-negativeIntegerswithoutConsecutiveOnes.cpp deleted file mode 100644 index 1a6e855..0000000 --- a/C_plus/600*_Non-negativeIntegerswithoutConsecutiveOnes.cpp +++ /dev/null @@ -1,44 +0,0 @@ -class Solution -{ -public: - int findIntegers(int n) - { - // k = 0 , 0 - // k = 1 , 0-1 - // k = 2 , 00-11 - // k = 3 , 000-111 - // k = 4 , 0000-1111 - - // f(k) , k = 5 00000-11111 ==> 00000-01111 和 10000-10111,因為11000不成立。 - // f(5 ) = f(4) + f(3) , f(4) = 00000-01111 , f(3) = 10000-10111 = 000-111 - // f[] = 1 2 3 5 8 13 21 34 55 - // findIntegers(1) = f(0) + 1 = 2 , 1 = 1 - // findIntegers(2) = f(1) + 1 = 3 , 2 = 10 - // findIntegers(3) = f(1) + f(0) = 3 , 3 = 11 ,在while迴圈中直接返回,因為出現連續兩個一 - // findIntegers(4) = f(2) + 1 = 4 , 4 = 100 - // findIntegers(5) = f(2) + f(0) + 1 = 5, 5 = 101 - // findIntegers(6) = f(2) + f(1) = 5, 6 = 110,在while迴圈中直接返回,因為出現連續兩個一 - - int ret = 0, k = 31, pre = 0; - vector f(32, 0); - f[0] = 1, f[1] = 2; - for (int i = 2; i < 31; ++i) - { - f[i] = f[i - 1] + f[i - 2]; - } - while (k >= 0) - { - if (n & (1 << k)) - { - ret += f[k]; - if (pre) - return ret; - pre = 1; - } - else - pre = 0; - k--; - } - return ret + 1; - } -}; \ No newline at end of file diff --git a/C_plus/606*_ConstructStringfromBinaryTree.cpp b/C_plus/606*_ConstructStringfromBinaryTree.cpp deleted file mode 100644 index ccb0c5d..0000000 --- a/C_plus/606*_ConstructStringfromBinaryTree.cpp +++ /dev/null @@ -1,34 +0,0 @@ -/* - * @Author: yuan - * @Date: 2021-07-16 20:50:06 - * @LastEditTime: 2021-07-16 20:50:06 - * @FilePath: /leet_code/C_plus/606*_ConstructStringfromBinaryTree.cpp - */ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution -{ -public: - string tree2str(TreeNode *root) - { - if (!root) - return ""; - string ret = to_string(root->val); - if (root->left) - ret += "(" + tree2str(root->left) + ")"; - else if (root->right) - ret += "()"; - if (root->right) - ret += "(" + tree2str(root->right) + ")"; - return ret; - } -}; \ No newline at end of file diff --git a/C_plus/611*_ValidTriangleNumber.cpp b/C_plus/611*_ValidTriangleNumber.cpp deleted file mode 100644 index db95cc4..0000000 --- a/C_plus/611*_ValidTriangleNumber.cpp +++ /dev/null @@ -1,34 +0,0 @@ -/* - * @Author: yuan - * @Date: 2021-07-15 22:23:40 - * @LastEditTime: 2021-07-15 22:23:41 - * @FilePath: /leet_code/C_plus/611*_ValidTriangleNumber.cpp - */ -class Solution -{ -public: - int triangleNumber(vector &nums) - { - sort(nums.begin(), nums.end()); - int ret = 0, n = nums.size(); - for (int i = 0; i < n; ++i) - { - for (int j = i + 1; j < n; j++) - { - int sum = nums[i] + nums[j]; - int left = j + 1, right = n; - while (left < right) - { - int mid = left + (right - left) / 2; - if (nums[mid] < sum) - left = mid + 1; - else - right = mid; - } - - ret += (right - 1 - j); - } - } - return ret; - } -}; \ No newline at end of file diff --git a/C_plus/617*_MergeTwoBinaryTrees.cpp b/C_plus/617*_MergeTwoBinaryTrees.cpp deleted file mode 100644 index fb495a2..0000000 --- a/C_plus/617*_MergeTwoBinaryTrees.cpp +++ /dev/null @@ -1,46 +0,0 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution -{ -public: - TreeNode *mergeTrees(TreeNode *root1, TreeNode *root2) - { - // option 1 - // if(!root1 && !root2) return nullptr; - // int val = 0; - // if(root1) val+= root1->val; - // if(root2) val+= root2->val; - // TreeNode *root = new TreeNode(val); - - // if(root1 && root2 ) root->left = mergeTrees(root1->left, root2->left); - // else if(!root1) root->left = mergeTrees(nullptr, root2->left); - // else if(!root2) root->left = mergeTrees(root1->left, nullptr); - - // if(root1 && root2 ) root->right = mergeTrees(root1->right, root2->right); - // else if(!root1) root->right = mergeTrees(nullptr, root2->right); - // else if(!root2) root->right = mergeTrees(root1->right, nullptr); - - // return root; - - // option 2 - if (!root1 && !root2) - return nullptr; - if (!root2) - return root1; - if (!root1) - return root2; - TreeNode *root = new TreeNode(root1->val + root2->val); - root->left = mergeTrees(root1->left, root2->left); - root->right = mergeTrees(root1->right, root2->right); - return root; - } -}; \ No newline at end of file diff --git a/C_plus/61_RotateList.cpp b/C_plus/61_RotateList.cpp deleted file mode 100644 index 6bb1718..0000000 --- a/C_plus/61_RotateList.cpp +++ /dev/null @@ -1,51 +0,0 @@ -/** - * Definition for singly-linked list. - * struct ListNode { - * int val; - * ListNode *next; - * ListNode() : val(0), next(nullptr) {} - * ListNode(int x) : val(x), next(nullptr) {} - * ListNode(int x, ListNode *next) : val(x), next(next) {} - * }; - */ -class Solution -{ -public: - ListNode *rotateRight(ListNode *head, int k) - { - if (head == nullptr || head->next == nullptr || k == 0) - return head; - - ListNode *p = head; - int len = 1; - // 串列長度 - while (p->next) - { - p = p->next; - len++; - } - p->next = head; // 串列變成cycle - cout << "length of list: " << len << endl; - - ListNode *start = head; - // 決定起點 - int n = len - k % len; - while (n) - { - start = start->next; - n--; - } - cout << "start's value: " << start->val << endl; - ListNode *res = start; - //決定終點 - len--; - while (len) - { - start = start->next; - len--; - } - start->next = nullptr; - - return res; - } -}; \ No newline at end of file diff --git a/C_plus/621*_TaskScheduler.cpp b/C_plus/621*_TaskScheduler.cpp deleted file mode 100644 index 4a5e22d..0000000 --- a/C_plus/621*_TaskScheduler.cpp +++ /dev/null @@ -1,38 +0,0 @@ -class Solution -{ -public: - int leastInterval(vector &tasks, int n) - { - // AAABBB - // A--A--A - // AB-AB-AB - // 計算字母出現次數最多為多少次 mx 3 - // 可以分為多少塊 mx-1 2 - // 每塊長度 A-- : n+1 3 - // 需要補idle的個數 25-i,出現最多次字母個數 - // 可以分為多少塊* 每塊長度 + 25-i = 2*3 + 2 - - // AAAABCDEFG n = 2 - // A--A--A--A--A 加入A - // AB-AB-AB-A--A 加入B - // ABCAB-AB-A--A 加入C - // ABCABDAB-A--A 加入D - // ABCABDABEA--A 加入E - // ABCABDABEAF-A 加入F - // ABCABDABEAFGA 加入G ans = 21 = 5*3 + 25-24 - - int size = tasks.size(); - vector vec(26, 0); - // 計算字母出現次數最多為多少次 mx - for (char c : tasks) - vec[c - 'A']++; - sort(vec.begin(), vec.end()); - int mx = vec[25]; - - int i = 25; - while (i > 0 && vec[i] == mx) - i--; - cout << i << " " << (mx - 1) << " " << (n + 1) << endl; - return max(size, (mx - 1) * (n + 1) + 25 - i); - } -}; \ No newline at end of file diff --git a/C_plus/622*_DesignCircularQueue.cpp b/C_plus/622*_DesignCircularQueue.cpp deleted file mode 100644 index ac415ba..0000000 --- a/C_plus/622*_DesignCircularQueue.cpp +++ /dev/null @@ -1,172 +0,0 @@ -// option 1 -class MyCircularQueue -{ -private: - vector data; - int size; - -public: - MyCircularQueue(int k) - { - size = k; - } - - bool enQueue(int value) - { - if (isFull()) - return false; - data.emplace_back(value); - return true; - } - - bool deQueue() - { - if (isEmpty()) - return false; - data.erase(data.begin()); - return true; - } - - int Front() - { - if (isEmpty()) - return -1; - return data.front(); - } - - int Rear() - { - if (isEmpty()) - return -1; - return data.back(); - } - - bool isEmpty() - { - return data.empty(); - } - - bool isFull() - { - return data.size() >= size; - } -}; - -/** - * Your MyCircularQueue object will be instantiated and called as such: - * MyCircularQueue* obj = new MyCircularQueue(k); - * bool param_1 = obj->enQueue(value); - * bool param_2 = obj->deQueue(); - * int param_3 = obj->Front(); - * int param_4 = obj->Rear(); - * bool param_5 = obj->isEmpty(); - * bool param_6 = obj->isFull(); - */ -// option 1 -class MyCircularQueue -{ -private: - vector data; - int size; - -public: - MyCircularQueue(int k) - { - size = k; - } - - bool enQueue(int value) - { - if (isFull()) - return false; - data.emplace_back(value); - return true; - } - - bool deQueue() - { - if (isEmpty()) - return false; - data.erase(data.begin()); - return true; - } - - int Front() - { - if (isEmpty()) - return -1; - return data.front(); - } - - int Rear() - { - if (isEmpty()) - return -1; - return data.back(); - } - - bool isEmpty() - { - return data.empty(); - } - - bool isFull() - { - return data.size() >= size; - } -}; - -// option 2 -class MyCircularQueue -{ -private: - vector data; - int size, front, rear; - -public: - MyCircularQueue(int k) - { - size = k; - front = 0; - rear = 0; - data.resize(k, -1); - } - - bool enQueue(int value) - { - if (isFull()) - return false; - data[rear] = value; - rear = (rear + 1) % size; - return true; - } - - bool deQueue() - { - if (isEmpty()) - return false; - data[front] = -1; - front = (front + 1) % size; - return true; - } - - int Front() - { - return data[front]; - } - - int Rear() - { - return data[(size + rear - 1) % size]; - } - - bool isEmpty() - { - return data[front] == -1 && front == rear; - } - - bool isFull() - { - return data[front] != -1 && front == rear; - } -}; diff --git a/C_plus/628_MamimumProductofThreeNumbers.cpp b/C_plus/628_MamimumProductofThreeNumbers.cpp deleted file mode 100644 index 1b4922e..0000000 --- a/C_plus/628_MamimumProductofThreeNumbers.cpp +++ /dev/null @@ -1,10 +0,0 @@ -class Solution -{ -public: - int maximumProduct(vector &nums) - { - int n = nums.size() - 1; - sort(nums.begin(), nums.end()); - return max(nums[0] * nums[1] * nums[n], nums[n - 2] * nums[n - 1] * nums[n]); - } -}; \ No newline at end of file diff --git a/C_plus/62_UniquePath.cpp b/C_plus/62_UniquePath.cpp deleted file mode 100644 index 556b964..0000000 --- a/C_plus/62_UniquePath.cpp +++ /dev/null @@ -1,48 +0,0 @@ -class Solution -{ -public: - int uniquePaths(int m, int n) - { - // option 1 dp - // vector> dp(m,vector(n,1)); - - // for(int i =1;i dp(n,1); - // for(int i=1;i smallestRange(vector > &nums) - { - - // [[4,10,15,24,26],[0,9,12,20],[5,18,22,30]] - - // [0,1],[4,0],[5,2],[9,1],[10,0],[12,1],[15,0],[18,2],[20,1],[22,2],[24,0],[26,0],[30,2] - - vector > v; - int n = nums.size(); - for (int i = 0; i < n; ++i) - { - for (int n : nums[i]) - v.push_back(make_pair(n, i)); - } - sort(v.begin(), v.end()); - // 對 v 做 Minimum Window Substring - int l = 0, valid = 0; - vector ret; - int diff = INT_MAX; - unordered_map window; // index 0-2 mapping freq - for (int r = 0; r < v.size(); r++) - { - auto c = v[r]; - - if (window[c.second] == 0) - valid++; - - window[c.second]++; - - while (valid == n && l <= r) - { - if (v[r].first - v[l].first < diff) - { - diff = v[r].first - v[l].first; - ret = {v[l].first, v[r].first}; - } - auto d = v[l++]; - - window[d.second]--; - if (window[d.second] == 0) - valid--; - } - } - return ret; - } -}; \ No newline at end of file diff --git a/C_plus/633_SumofSquareNumbers.cpp b/C_plus/633_SumofSquareNumbers.cpp deleted file mode 100644 index f48705a..0000000 --- a/C_plus/633_SumofSquareNumbers.cpp +++ /dev/null @@ -1,73 +0,0 @@ -class Solution -{ -public: - bool search(long l, long r, long target) - { - - while (l <= r) - { - long mid = l + (r - l) / 2; - if (mid * mid == target) - return true; - else if (mid * mid < target) - l = mid + 1; - else - r = mid - 1; - } - return false; - } - - bool judgeSquareSum(int c) - { - - // option 1 two pointer O(n) - // 5 = 1*1 + 2*2 - // 10 = 1*1 + 3*3 - // 13 = 2*2 + 3*3 - // - // 找哪兩個數字 - int l = 0, r = sqrt(c); - // l 可以等於 r - while (l <= r) - { - // overflow - // int sum = l*l + r*r; - // if(sum == c) return true; - // else if(sum < c) l++; - // else r--; - - // avoid overflow - int sum = c - l * l; - if (sum == r * r) - return true; - else if (sum > r * r) - l++; - else - r--; - } - return false; - - // option 2 binary search O(logn) - bool ret = false; - - if (c < 0) - return ret; - - if (c == 0 || c == 1) - return true; - - for (long long i = 0; i * i <= c; ++i) - { - long target = c - i * i; - - // 能不能找出 一個數字 其平方為 target, - if (search(0, target, target)) - { - ret = true; - break; - } - } - - return ret; - } -}; \ No newline at end of file diff --git a/C_plus/637_AverageofLevelsinBinaryTree.cpp b/C_plus/637_AverageofLevelsinBinaryTree.cpp deleted file mode 100644 index e982edf..0000000 --- a/C_plus/637_AverageofLevelsinBinaryTree.cpp +++ /dev/null @@ -1,40 +0,0 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution -{ -public: - vector averageOfLevels(TreeNode *root) - { - if (!root) - return {}; - vector ret; - queue q; - q.push(root); - while (!q.empty()) - { - int size = q.size(); - double avg = 0.0; - for (int i = 0; i < size; ++i) - { - TreeNode *p = q.front(); - q.pop(); - avg += p->val; - if (p->left) - q.push(p->left); - if (p->right) - q.push(p->right); - } - ret.push_back(avg / size); - } - return ret; - } -}; \ No newline at end of file diff --git a/C_plus/63_UniquPathsII.cpp b/C_plus/63_UniquPathsII.cpp deleted file mode 100644 index 4143bc3..0000000 --- a/C_plus/63_UniquPathsII.cpp +++ /dev/null @@ -1,36 +0,0 @@ -class Solution -{ -public: - int uniquePathsWithObstacles(vector > &obstacleGrid) - { - // option 1 dp - int m = obstacleGrid.size(), n = obstacleGrid[0].size(); - if (obstacleGrid[0][0] == 1) - return 0; - vector > dp(m, vector(n, 0)); - dp[0][0] = (obstacleGrid[0][0] == 1) ? 0 : 1; - for (int i = 0; i < m; ++i) - { - for (int j = 0; j < n; ++j) - { - if (obstacleGrid[i][j] == 0) - { - if (i == 0 && j == 0) - continue; - else if (i == 0) - dp[i][j] = dp[i][j - 1]; - else if (j == 0) - dp[i][j] = dp[i - 1][j]; - else - dp[i][j] = dp[i - 1][j] + dp[i][j - 1]; - } - } - } - return dp[m - 1][n - 1]; - - // option 壓縮為 一維 dp - } -}; - - - diff --git a/C_plus/641*_DesignCircularDeque.cpp b/C_plus/641*_DesignCircularDeque.cpp deleted file mode 100644 index d9c0cfe..0000000 --- a/C_plus/641*_DesignCircularDeque.cpp +++ /dev/null @@ -1,160 +0,0 @@ -// option 1 -// class MyCircularDeque { -// private: -// vector data; -// int size, tail, head; -// public: -// /** Initialize your data structure here. Set the size of the deque to be k. */ -// MyCircularDeque(int k) { -// size=k; -// head = 0; -// tail = 0; - -// } - -// /** Adds an item at the front of Deque. Return true if the operation is successful. */ -// bool insertFront(int value) { -// if(isFull()) return false; -// data.emplace(data.begin(), value); -// return true; -// } - -// /** Adds an item at the rear of Deque. Return true if the operation is successful. */ -// bool insertLast(int value) { -// if(isFull()) return false; -// data.emplace_back(value); -// return true; -// } - -// /** Deletes an item from the front of Deque. Return true if the operation is successful. */ -// bool deleteFront() { -// if(isEmpty()) return false; -// // data.pop_front(); -// data.erase(data.begin()); -// return true; -// } - -// /** Deletes an item from the rear of Deque. Return true if the operation is successful. */ -// bool deleteLast() { -// if(isEmpty()) return false; -// data.pop_back(); -// return true; -// } - -// /** Get the front item from the deque. */ -// int getFront() { -// if(isEmpty()) return -1; -// return data.front(); -// } - -// /** Get the last item from the deque. */ -// int getRear() { -// if(isEmpty()) return -1; -// return data.back(); -// } - -// /** Checks whether the circular deque is empty or not. */ -// bool isEmpty() { -// return data.empty(); -// } - -// /** Checks whether the circular deque is full or not. */ -// bool isFull() { -// return data.size()>=size; -// } -// }; - -// option 2 -class MyCircularDeque -{ -private: - vector data; - int front, rear, size; - -public: - /** Initialize your data structure here. Set the size of the deque to be k. */ - MyCircularDeque(int k) - { - size = k; - front = 0; - rear = 0; - data.resize(k, -1); - } - - /** Adds an item at the front of Deque. Return true if the operation is successful. */ - bool insertFront(int value) - { - if (isFull()) - return false; - front = (size + front - 1) % size; - data[front] = value; - return true; - } - - /** Adds an item at the rear of Deque. Return true if the operation is successful. */ - bool insertLast(int value) - { - if (isFull()) - return false; - data[rear] = value; - rear = (rear + 1) % size; - return true; - } - - /** Deletes an item from the front of Deque. Return true if the operation is successful. */ - bool deleteFront() - { - if (isEmpty()) - return false; - data[front] = -1; - front = (front + 1) % size; - return true; - } - - /** Deletes an item from the rear of Deque. Return true if the operation is successful. */ - bool deleteLast() - { - if (isEmpty()) - return false; - rear = (size + rear - 1) % size; - data[rear] = -1; - return true; - } - - /** Get the front item from the deque. */ - int getFront() - { - return data[front]; - } - - /** Get the last item from the deque. */ - int getRear() - { - return data[(size + rear - 1) % size]; - } - - /** Checks whether the circular deque is empty or not. */ - bool isEmpty() - { - return front == rear && data[front] == -1; - } - - /** Checks whether the circular deque is full or not. */ - bool isFull() - { - return front == rear && data[front] != -1; - } -}; - -/** - * Your MyCircularDeque object will be instantiated and called as such: - * MyCircularDeque* obj = new MyCircularDeque(k); - * bool param_1 = obj->insertFront(value); - * bool param_2 = obj->insertLast(value); - * bool param_3 = obj->deleteFront(); - * bool param_4 = obj->deleteLast(); - * int param_5 = obj->getFront(); - * int param_6 = obj->getRear(); - * bool param_7 = obj->isEmpty(); - * bool param_8 = obj->isFull(); - */ \ No newline at end of file diff --git a/C_plus/645*_SetMismatch.cpp b/C_plus/645*_SetMismatch.cpp deleted file mode 100644 index 041bdd8..0000000 --- a/C_plus/645*_SetMismatch.cpp +++ /dev/null @@ -1,51 +0,0 @@ -class Solution -{ -public: - vector findErrorNums(vector &nums) - { - - // option 1 O(n) time and O(N) space - // unordered_map mp; - // for(int n:nums) mp[n]++; - // vector ret; - // for(int n =1 ;n<=nums.size() ;++n){ - // if(mp.count(n) && mp[n] == 2) ret.push_back(n); // twice number - // } - // for(int n =1 ;n<=nums.size() ;++n){ - // if(!mp.count(n)) ret.push_back(n); // missing number - // } - // return ret; - - // option 2 - // a^a = 0 , a^0 = a,如果數字都放對的話,index^val = 0 - // 再加上 ^ 符合交換率 - // 拜訪過的index-1 給他相反數 - //index 1 2 3 4 5 6 7 8 9 - //val 1 2 3 4 5 6 7 8 9 - // 0 1 2 3 - // 1 2 2 4 - // -1 -2 2 -4 - // + - int dup; - for (int i = 0; i < nums.size(); i++) - { - int index = abs(nums[i]) - 1; - - if (nums[index] < 0) - dup = abs(nums[i]); - else - { - nums[index] *= -1; - } - } - int missing = -1; - for (int i = 0; i < nums.size(); ++i) - { - if (nums[i] > 0) - { - missing = i + 1; - } - } - return {dup, missing}; - } -}; \ No newline at end of file diff --git a/C_plus/647*_PalindromicSubstrings.cpp b/C_plus/647*_PalindromicSubstrings.cpp deleted file mode 100644 index 284af3d..0000000 --- a/C_plus/647*_PalindromicSubstrings.cpp +++ /dev/null @@ -1,68 +0,0 @@ -class Solution -{ -public: - int countSubstrings(string s) - { - // option 1 brute force - int n = s.size(); - int ret = 0; - for (int i = 0; i < n; ++i) - { - int l = i, r = i; - while (l > -1 && r < n && s[l] == s[r]) - { - l--; - r++; - ret++; - } - // 子回文字串長度 為偶數 - l = i, r = i + 1; - while (l > -1 && r < n && s[l] == s[r]) - { - l--; - r++; - ret++; - } - } - return ret; - - // option 2 dp - class Solution - { - public: - int countSubstrings(string s) - { - // dp - // a a a - //a t t t - //a f t t - //a f f t - - // a b c - //a t f f - //b t f - //c t - int n = s.size(); - vector > dp(n, vector(n)); - int ret = 0; - //base case - for (int i = 0; i < n; ++i) - dp[i][i] = true; - ret += n; - - for (int i = n - 2; i > -1; i--) - { - for (int j = i + 1; j < n; ++j) - { - if (s[i] == s[j]) - dp[i][j] = (j - i <= 2) || dp[i + 1][j - 1]; - - if (dp[i][j]) - ++ret; - } - } - return ret; - } - }; - } -}; \ No newline at end of file diff --git a/C_plus/64_MinimunPathSum.cpp b/C_plus/64_MinimunPathSum.cpp deleted file mode 100644 index b8230b0..0000000 --- a/C_plus/64_MinimunPathSum.cpp +++ /dev/null @@ -1,68 +0,0 @@ -class Solution -{ -public: - vector > memo; - int dp(vector > &grid, int i, int j) - { - if (i == 0 && j == 0) - return grid[0][0]; - - if (i < 0 || j < 0) - return INT_MAX; - - if (memo[i][j] != -1) - return memo[i][j]; - memo[i][j] = min(dp(grid, i - 1, j), dp(grid, i, j - 1)) + grid[i][j]; - return memo[i][j]; - - // return grid[i][j] + min(dp(grid, i-1,j ), dp(grid, i, j-1) ); - } - int minPathSum(vector > &grid) - { - - // option 0 brute force recursive -> time out - - // int m = grid.size(), n = grid[0].size(); - // return dp(grid, m-1, n-1); - - // option 1 重疊子問題 memo pattern up-bottom O(MN) space and time - // int m = grid.size(), n = grid[0].size(); - // // 初始化memo - // memo = vector>(m, vector(n, -1)); - // return dp(grid, m-1, n-1); - - // option 2 dp bottom-up O(MN) space and time - // int m = grid.size(), n = grid[0].size(); - // vector> dp(grid.begin(), grid.end()); - - // for(int i=1;i dp(n, 0); - // 初始化dp - dp[0] = grid[0][0]; - for (int j = 1; j < n; ++j) - dp[j] = grid[0][j] + dp[j - 1]; - for (int i = 1; i < m; ++i) - { - for (int j = 0; j < n; ++j) - { - if (j == 0) - dp[j] = dp[j] + grid[i][j]; - else - dp[j] = min(dp[j], dp[j - 1]) + grid[i][j]; - } - } - return dp[n - 1]; - } -}; \ No newline at end of file diff --git a/C_plus/652*_FindDuplicateSubtrees.cpp b/C_plus/652*_FindDuplicateSubtrees.cpp deleted file mode 100644 index 23f1aa0..0000000 --- a/C_plus/652*_FindDuplicateSubtrees.cpp +++ /dev/null @@ -1,44 +0,0 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution -{ -private: - unordered_map memo; - vector res; - -public: - string traverse(TreeNode *root) - { - // postorder,因為必須要先知道左右子樹長怎樣,再加上根節點去構建 - // 用字符串列 "," 將二元樹序列化 - // 利用hash外部資料結構,將自己子樹序列化結果存進去 - if (!root) - return "#"; - - string left = traverse(root->left); - string right = traverse(root->right); - - string key = left + "," + right + "," + to_string(root->val); - // 如果有重複的話,只會存一次 - if (memo.count(key) && memo[key] == 1) - res.push_back(root); - - memo[key]++; - return key; - } - vector findDuplicateSubtrees(TreeNode *root) - { - - traverse(root); - return res; - } -}; \ No newline at end of file diff --git a/C_plus/653*_TwoSumIV-InputisaBST.cpp b/C_plus/653*_TwoSumIV-InputisaBST.cpp deleted file mode 100644 index 1eb9d6e..0000000 --- a/C_plus/653*_TwoSumIV-InputisaBST.cpp +++ /dev/null @@ -1,72 +0,0 @@ -/* - * @Author: yuan - * @Date: 2021-07-16 21:49:27 - * @LastEditTime: 2021-07-16 21:49:27 - * @FilePath: /leet_code/C_plus/653*_TwoSumIV-InputisaBST.cpp - */ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution -{ -private: - unordered_set s; - -public: - // void inorder(TreeNode *root, vector & vec){ - // if(!root) return ; - - // inorder(root->left, vec); - // vec.push_back(root->val); - // inorder(root->right, vec); - // } - bool findTarget(TreeNode *root, int k) - { - // option 1 利用vector紀錄每一個節點 O(n) tiem and O(n) space - // vector vec; - // inorder(root, vec); - // // two pointer - // int l =0,r= vec.size()-1; - // while(lval)) - return true; - s.insert(root->val); - return findTarget(root->left, k) || findTarget(root->right, k); - - - // option 2.1 BFS +queue - unordered_set s; - queue q; - q.push(root); - while(!q.empty()){ - TreeNode *p = q.front(); - q.pop(); - if(s.count(k - p->val )) return true; - s.insert(p->val); - if(p->left) q.push(p->left); - if(p->right) q.push(p->right); - - - } - - return false; - - } -}; \ No newline at end of file diff --git a/C_plus/654*_MaximumBinaryTree.cpp b/C_plus/654*_MaximumBinaryTree.cpp deleted file mode 100644 index 8d1a58a..0000000 --- a/C_plus/654*_MaximumBinaryTree.cpp +++ /dev/null @@ -1,42 +0,0 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution -{ -public: - TreeNode *constructMaximumBinaryTree(vector &nums, int lo, int hi) - { - // preorder - // 找到最大值,並記下index - if (lo > hi) - return nullptr; - int index = -1, maxVal = INT_MIN; - for (int i = lo; i <= hi; ++i) - { - if (nums[i] > maxVal) - { - maxVal = nums[i]; - index = i; - } - } - TreeNode *root = new TreeNode(nums[index]); - root->left = constructMaximumBinaryTree(nums, lo, index - 1); - root->right = constructMaximumBinaryTree(nums, index + 1, hi); - return root; - } - TreeNode *constructMaximumBinaryTree(vector &nums) - { - if (nums.empty()) - return nullptr; - // overload - return constructMaximumBinaryTree(nums, 0, nums.size() - 1); - } -}; \ No newline at end of file diff --git a/C_plus/658*_FindKClosestElements.cpp b/C_plus/658*_FindKClosestElements.cpp deleted file mode 100644 index c80cd23..0000000 --- a/C_plus/658*_FindKClosestElements.cpp +++ /dev/null @@ -1,47 +0,0 @@ -class Solution -{ -public - List findClosestElements(int[] arr, int k, int x) - { - //find the cloest element, r is the index of the cloest element - int l = 0, r = arr.length - 1; - while (l <= r) - { - int mid = (l + r) / 2; - if (arr[mid] == x) - { - r = mid; - break; - } - else if (arr[mid] > x) - r = mid - 1; - else - l = mid + 1; - } - - //ensure the range - l = r; - r++; - while (k > 0) - { - if (r >= arr.length || (l >= 0 && x - arr[l] <= arr[r] - x)) - { - l--; - } - else - { - r++; - } - - k--; - } - System.out.println(l + 1); - System.out.println(r); - List list = new ArrayList<>(); - for (int i = l + 1; i < r; i++) - { - list.add(arr[i]); - } - return list; - } -} \ No newline at end of file diff --git a/C_plus/659*_SplitArrayintoConsecutiveSubsequences.cpp b/C_plus/659*_SplitArrayintoConsecutiveSubsequences.cpp deleted file mode 100644 index efa40e8..0000000 --- a/C_plus/659*_SplitArrayintoConsecutiveSubsequences.cpp +++ /dev/null @@ -1,48 +0,0 @@ -class Solution -{ -public: - bool isPossible(vector &nums) - { - if (nums.size() < 3) - return false; - - // hash table freq 紀錄每個元素出現的次數,以幫助一個元素判斷自己是作為開頭, - // hash table need 紀錄乃些元素可以被接到提他子序列後面,幫助一個元素判斷自己是否可以被接到其他序列後面 - unordered_map freq, need; - for (int n : nums) - freq[n]++; - - for (int n : nums) - { - if (freq[n] == 0) - continue; - - // 先判断 n 是否能接到其他子序列后面 - if (need.count(n) && need[n] > 0) - { - // n 可以接到之前的某个序列后面 - freq[n]--; - // 对 n 的需求减一 - need[n]--; - // 对 n + 1 的需求加一 - need[n + 1]++; - } - else if (freq[n] > 0 && freq[n + 1] > 0 && freq[n + 2] > 0) - { - // 将 n 作为开头,新建一个长度为 3 的子序列 [n,n+1,n+2] - freq[n]--; - freq[n + 1]--; - freq[n + 2]--; - // 对 n + 3 的需求加一 - need[n + 3]++; - } - else - { - // 两种情况都不符合,则无法分配 - return false; - } - } - - return true; - } -}; \ No newline at end of file diff --git a/C_plus/66*_PlusOne.cpp b/C_plus/66*_PlusOne.cpp deleted file mode 100644 index 213ad62..0000000 --- a/C_plus/66*_PlusOne.cpp +++ /dev/null @@ -1,24 +0,0 @@ -class Solution -{ -public: - vector plusOne(vector &digits) - { - // vector ret; - int value = 0; - int n = digits.size(); - for (int i = n - 1; i >= 0; --i) - { - if (digits[i] == 9) - digits[i] = 0; - else - { - digits[i]++; - return digits; - } - } - - if (digits.front() == 0) - digits.insert(digits.begin(), 1); - return digits; - } -}; \ No newline at end of file diff --git a/C_plus/671_SecondMinimumNodeInaBinaryTree.cpp b/C_plus/671_SecondMinimumNodeInaBinaryTree.cpp deleted file mode 100644 index 7ad9eb7..0000000 --- a/C_plus/671_SecondMinimumNodeInaBinaryTree.cpp +++ /dev/null @@ -1,51 +0,0 @@ -/* - * @Author: yuan - * @Date: 2021-07-16 22:02:10 - * @LastEditTime: 2021-07-16 22:02:10 - * @FilePath: /leet_code/C_plus/671_SecondMinimumNodeInaBinaryTree.cpp - */ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution -{ -public: - void inorder(TreeNode *root, vector &vec) - { - if (!root) - return; - inorder(root->left, vec); - vec.push_back(root->val); - inorder(root->right, vec); - } - int findSecondMinimumValue(TreeNode *root) - { - // 用vector紀錄所有節點 - int ret = -1; - int mn = INT_MAX; - vector vec; - inorder(root, vec); - sort(vec.begin(), vec.end()); - int n = vec.size(); - if (vec[0] == vec[n - 1] || n == 1) - return ret; - mn = vec[0]; - for (int i = 1; i < n; ++i) - { - if (vec[i] > mn) - { - ret = vec[i]; - break; - } - } - return ret; - } -}; \ No newline at end of file diff --git a/C_plus/674_LongestContinuousIncreasingSubsequence.cpp b/C_plus/674_LongestContinuousIncreasingSubsequence.cpp deleted file mode 100644 index 6a5584a..0000000 --- a/C_plus/674_LongestContinuousIncreasingSubsequence.cpp +++ /dev/null @@ -1,23 +0,0 @@ -class Solution -{ -public: - int findLengthOfLCIS(vector &nums) - { - - int ret = 0, temp = 1; - int n = nums.size(); - if (n == 1) - return 1; - for (int i = 1; i < n; ++i) - { - if (nums[i] > nums[i - 1]) - temp++; - else - { - ret = max(ret, temp); - temp = 1; - } - } - return max(ret, temp); - } -}; \ No newline at end of file diff --git a/C_plus/678*_ValidParentesisString.cpp b/C_plus/678*_ValidParentesisString.cpp deleted file mode 100644 index 7d34e6e..0000000 --- a/C_plus/678*_ValidParentesisString.cpp +++ /dev/null @@ -1,34 +0,0 @@ -class Solution -{ -public: - bool checkValidString(string s) - { - // record index - stack sta, star; - for (int i = 0; i < s.size(); ++i) - { - if (s[i] == '(') - sta.push(i); - else if (s[i] == '*') - star.push(i); - else - { - if (sta.empty() && star.empty()) - return false; - else if (!sta.empty()) - sta.pop(); - else - star.pop(); - } - } - - while (!sta.empty() && !star.empty()) - { - if (sta.top() > star.top()) - return false; - sta.pop(); - star.pop(); - } - return sta.empty(); - } -}; \ No newline at end of file diff --git a/C_plus/67_AddBinary.cpp b/C_plus/67_AddBinary.cpp deleted file mode 100644 index 60acdd9..0000000 --- a/C_plus/67_AddBinary.cpp +++ /dev/null @@ -1,48 +0,0 @@ -class Solution -{ -public: - string addBinary(string a, string b) - { - - int len = max(a.size(), b.size()); - for (int i = a.size(); i < len; ++i) - a = "0" + a; - for (int i = b.size(); i < len; ++i) - b = "0" + b; - - int sum = 0; - int carry = 0; - string ret = ""; - int i = a.size() - 1; - int j = b.size() - 1; - while (i >= 0 || j >= 0) - { - sum = carry; - sum += a[i--] - '0'; - sum += b[j--] - '0'; - - if (sum >= 2) - carry = sum / 2; - else - carry = 0; - // if(sum==3){ - // carry = sum/2; - // } - // else if(sum==2){ - // carry = sum/2; - // } - // else if(sum==1){ - // carry = 0; - // } - // else if(sum==0){ - // carry = 0; - // } - ret = to_string(sum % 2) + ret; - } - if (carry > 0) - { - ret = to_string(carry % 2) + ret; - } - return ret; - } -}; \ No newline at end of file diff --git a/C_plus/69*_Sqrt(x).cpp b/C_plus/69*_Sqrt(x).cpp deleted file mode 100644 index 5636a18..0000000 --- a/C_plus/69*_Sqrt(x).cpp +++ /dev/null @@ -1,19 +0,0 @@ -class Solution { -public: - int mySqrt(int x) { - // return sqrt(x); - - - // option 1 - // binary search - if (x <= 1) return x; - int left = 0, right = x; - while (left < right) { - cout<= mid) left = mid + 1; - else right = mid; - } - return right - 1; - } -}; \ No newline at end of file diff --git a/C_plus/693_BinaryNumberwithAlternatingBits.cpp b/C_plus/693_BinaryNumberwithAlternatingBits.cpp deleted file mode 100644 index ccd1232..0000000 --- a/C_plus/693_BinaryNumberwithAlternatingBits.cpp +++ /dev/null @@ -1,19 +0,0 @@ -class Solution -{ -public: - bool hasAlternatingBits(int n) - { - int pre = (n & 1); - n >>= 1; - while (n) - { - if (pre == 0 && (n & 1) == 0) - return false; - if (pre * (n & 1) == 1) - return false; - pre = n & 1; - n >>= 1; - } - return true; - } -}; \ No newline at end of file diff --git a/C_plus/695_MaxAreaofIsland.cpp b/C_plus/695_MaxAreaofIsland.cpp deleted file mode 100644 index aa47078..0000000 --- a/C_plus/695_MaxAreaofIsland.cpp +++ /dev/null @@ -1,63 +0,0 @@ -class Solution -{ -public: - void traverse(vector > &grid, int i, int j, vector > &visited, int &area) - { - int n = grid.size(), m = grid[0].size(); - if (i < 0 || i > n - 1 || j < 0 || j > m - 1 || visited[i][j] || grid[i][j] == 0) - return; - visited[i][j] = true; - area++; - traverse(grid, i - 1, j, visited, area); - traverse(grid, i, j - 1, visited, area); - traverse(grid, i + 1, j, visited, area); - traverse(grid, i, j + 1, visited, area); - } - int maxAreaOfIsland(vector > &grid) - { - // option 1 DFS - int ret = 0; - int n = grid.size(), m = grid[0].size(); - vector > visited(n, vector(m, false)); - for (int i = 0; i < n; ++i) - { - for (int j = 0; j < m; ++j) - { - if (grid[i][j] == 0 || visited[i][j]) - continue; - int area = 0; - traverse(grid, i, j, visited, area); - ret = max(ret, area); - } - } - return ret; - // option 2 DFS without space - // 將拜訪過的改成0 - } -}; - - -// option 2 -void dfs(vector>& grid, int i, int j){ - int n = grid.size(), m = grid[0].size(); - if(i<0 || j<0 || i>n-1 || j>m-1 || grid[i][j]=='0') return; - - grid[i][j] = '0'; - dfs(grid, i-1,j); - dfs(grid, i,j-1); - dfs(grid, i+1,j); - dfs(grid, i,j+1); - - } - int numIslands(vector>& grid) { - int cnt = 0; - int n = grid.size(), m = grid[0].size(); - for(int i=0;i &nums, int index, vector &bucket, int target) - { - - if (index == nums.size()) - { - // 檢查每個桶數字之和是否都是 target - for (int b : bucket) - { - if (b != target) - return false; - } - return true; - } - - // for(int i = ; i target) - continue; - // 選擇裝進 第 i 個桶子 - bucket[i] += nums[index]; - - // 遞回窮舉下一個數字的選擇 - if (NumberTraverse(nums, index + 1, bucket, target)) - return true; - // 撤銷選擇 - bucket[i] -= nums[index]; - } - // nums[index] 裝到哪個桶都不行 - return false; - } - bool canPartitionKSubsets(vector &nums, int k) - { - - int target = 0; - for (int n : nums) - target += n; - if (target % k != 0) - return false; - target /= k; - - // option 1 以 這 n 個數字的視角,每個數字都要選則進入 k 個桶的某一個 - // 原始版本會 Time Limit Exceeded - // 事先排序降序,並在NumberTraverse 遍歷時加入判斷 - // sort(nums.begin(), nums.end(),greater() ); //或 sort(nums.rbegin(),nums.rend()); - // vector bucket(k); - - // return NumberTraverse(nums, 0, bucket, target); - - // option 2 以 這 k 個桶子的視角,對於每個桶都要遍歷nums 中的 n 個數字,然後選擇是否將當前遍歷的數字裝到自己這個桶子里 - // 從第 k 個桶開始 - vector used(nums.size(), false); - - return BucketTraverse(nums, k, 0, used, 0, target); - } - bool BucketTraverse(vector &nums, int k, int bucketSum, vector &used, int start, int target) - { - // base case - if (k == 0) - { - // 所有桶都被裝滿,而且 nums 一定都用完了 - // 因為 target == sum /k - return true; - } - if (bucketSum == target) - { - // 當前的桶子 k 裝滿了,需要換下一個桶子 - return BucketTraverse(nums, k - 1, 0, used, 0, target); - } - // 改成遞回方式 - for (int i = start; i < nums.size(); ++i) - { - // 剪枝,拜訪 沒拜訪過的 - if (used[i] == false) - { - // 剪枝,該桶子裝不下 nums[i] - if (bucketSum + nums[i] > target) - continue; - - // 選擇裝進 第 i 個數字 到 第 k 個桶 - used[i] = true; - bucketSum += nums[i]; - if (BucketTraverse(nums, k, bucketSum, used, i + 1, target)) - return true; - // 撤銷選擇 - used[i] = false; - bucketSum -= nums[i]; - } - } - return false; - - // // 直到所有桶都裝滿 - // while(k > 0){ - // // 紀錄當前桶數字之和 - // int bucketSum = 0; - // for(int i=0;ileft, val); - - if (root->val == val) - { - ans = root; - return; - } - - traverse(root->right, val); - } - - TreeNode *searchBST(TreeNode *root, int val) - { - - // option 1 brute force whether it is BST - // ans = new TreeNode(-1); - // traverse(root, val); - // if(ans->val == -1) return nullptr; - // return ans; - - // option 1.1 imroved using BST - if (!root) - return nullptr; - // V 找到目標 - if (root->val == val) - return root; - // L - else if (root->val < val) - return searchBST(root->right, val); - // R - else - return searchBST(root->left, val); - - // option 2 meaningless iterative + stack support - // if(!root) return nullptr; - // stack sta; - // TreeNode *q = root; - // while(q || !sta.empty()){ - // // L - // while(q){ - // sta.push(q); - // q = q->left; - // } - // q = sta.top(); - // sta.pop(); - // // V 找到目標 - // if(q->val == val) return q; - // // R - // q=q->right; - // } - // return nullptr; - } -}; \ No newline at end of file diff --git a/C_plus/701*_InsertintoaBinarySearchTree.cpp b/C_plus/701*_InsertintoaBinarySearchTree.cpp deleted file mode 100644 index 78f62b2..0000000 --- a/C_plus/701*_InsertintoaBinarySearchTree.cpp +++ /dev/null @@ -1,56 +0,0 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution -{ -public: - TreeNode *insertIntoBST(TreeNode *root, int val) - { - // option 1 recursive without adjust - // // 增刪查改 涉及到改函數就要返回 TreeNode 類型 - // // base case 找到空位置 - // if(!root) return new TreeNode(val); - - // // 假設不會有插入重複的元素 - // // if(root->val == val) - - // if(root->val < val) root->right = insertIntoBST(root->right, val); - // if(root->val > val) root->left = insertIntoBST(root->left, val); - // return root; - - // option 2 iterative - if (!root) - return new TreeNode(val); - TreeNode *cur = root; - while (true) - { - if (cur->val > val) - { // 往左子樹搜尋 - if (!cur->left) - { - cur->left = new TreeNode(val); - break; - } - cur = cur->left; - } - else if (cur->val < val) - { // 往右子樹搜尋 - if (!cur->right) - { - cur->right = new TreeNode(val); - break; - } - cur = cur->right; - } - } - return root; - } -}; \ No newline at end of file diff --git a/C_plus/703*_KthLargestElemeninaStream.cpp b/C_plus/703*_KthLargestElemeninaStream.cpp deleted file mode 100644 index bf025ed..0000000 --- a/C_plus/703*_KthLargestElemeninaStream.cpp +++ /dev/null @@ -1,38 +0,0 @@ -/* - * @Author: yuan - * @Date: 2021-07-17 09:07:52 - * @LastEditTime: 2021-07-17 09:07:53 - * @FilePath: /leet_code/C_plus/703*_KthLargestElemeninaStream.cpp - */ -class KthLargest -{ -private: - priority_queue, greater > q; - int ans; - -public: - KthLargest(int k, vector &nums) - { - ans = k; - for (int num : nums) - { - q.push(num); - if (q.size() > ans) - q.pop(); - } - } - - int add(int val) - { - q.push(val); - if (q.size() > ans) - q.pop(); - return q.top(); - } -}; - -/** - * Your KthLargest object will be instantiated and called as such: - * KthLargest* obj = new KthLargest(k, nums); - * int param_1 = obj->add(val); - */ \ No newline at end of file diff --git a/C_plus/704_BinarySearch.cpp b/C_plus/704_BinarySearch.cpp deleted file mode 100644 index b955069..0000000 --- a/C_plus/704_BinarySearch.cpp +++ /dev/null @@ -1,82 +0,0 @@ -class Solution -{ -public: - int search(vector &nums, int target) - { - // version 1 - // int l = 0, r= nums.size()-1; // 注意 - // 搜索區間[l, r] - // while(l<=r){ - // int mid = l + (r-l)/2; - // if(nums[mid] == target) return mid; - // else if(nums[mid]< target) l = mid+1; // 注意 - // else if(nums[mid]>target) r= mid-1; // 注意 - // } - // return -1; - - // version 2 - int l = 0, r = nums.size(); - // 搜索區間[l, r) - while (l < r) - { // 終止條件 l==r - int mid = l + (r - l) / 2; - if (nums[mid] == target) - return mid; - else if (nums[mid] < target) - l = mid + 1; - else if (nums[mid] > target) - r = mid; - } - return nums[l] == target ? l : -1; - - // option 3 left bound - int n = nums.size(); - int l = 0, r = n; - while (l < r) - { - int mid = l + (r - l) / 2; - if (nums[mid] == target) - r = mid; - else if (nums[mid] < target) - l = mid + 1; - else - r = mid; - } - return l < n && nums[l] == target ? l : -1; - - // right bound - // int l = 0, r = nums.size(); - // while(l= nums.size() || nums[l] != target) - return -1; - return l; - //right bound - // if(r<0 || nums[r]!=target) return -1; - // return r; - } -}; \ No newline at end of file diff --git a/C_plus/705*_DesignHashSet.cpp b/C_plus/705*_DesignHashSet.cpp deleted file mode 100644 index 23c8fc3..0000000 --- a/C_plus/705*_DesignHashSet.cpp +++ /dev/null @@ -1,64 +0,0 @@ -class MyHashSet -{ -private: - // unordered_set st; - vector vec; // Time: O(1) Space: O(n) - // vector> table; - int bucket; - -public: - /** Initialize your data structure here. */ - MyHashSet() - { - vec = vector(1000001, false); - - // 共 1000 桶子,用key 取餘數,判斷放在哪個桶子 - - // bucket = 1000; - // table = vector>(bucket); - } - - void add(int key) - { - // if(st.count(key)) return; - // st.insert(key); - vec[key] = true; - - // 用key 取餘數,判斷放在哪個桶子 - // int k = key%bucket; - // std::list::iterator findIter = std::find(table[k].begin(), table[k].end(), key); - // if(findIter != table[k].end()) return ; - // table[k].push_back(key); - } - - void remove(int key) - { - // if(!st.count(key)) return ; - // st.erase(key); - vec[key] = false; - - // int k = key%bucket; - // std::list::iterator findIter = std::find(table[k].begin(), table[k].end(), key); - // if(findIter ==table[k].end() ) return ; - // table[k].remove(key); - } - - /** Returns true if this set contains the specified element */ - bool contains(int key) - { - // return st.count(key); - return vec[key]; - - // int k = key%bucket; - // std::list::iterator findIter = std::find(table[k].begin(), table[k].end(), key); - // return findIter ==table[k].end()?false:true; - } -}; - -/** - * Your MyHashSet object will be instantiated and called as such: - * MyHashSet* obj = new MyHashSet(); - * obj->add(key); - * obj->remove(key); - * bool param_3 = obj->contains(key); - */ \ No newline at end of file diff --git a/C_plus/706*_DesignHashMap.cpp b/C_plus/706*_DesignHashMap.cpp deleted file mode 100644 index 62060ec..0000000 --- a/C_plus/706*_DesignHashMap.cpp +++ /dev/null @@ -1,34 +0,0 @@ -class MyHashMap { -private: - vector data; -public: - /** Initialize your data structure here. */ - MyHashMap() { - data.resize(1000001,-1); - } - - /** value will always be non-negative. */ - void put(int key, int value) { - data[key] = value; - } - - /** Returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key */ - int get(int key) { - return data[key]; - } - - /** Removes the mapping of the specified value key if this map contains a mapping for the key */ - void remove(int key) { - data[key] = -1; - } -}; - -/** - * Your MyHashMap object will be instantiated and called as such: - * MyHashMap* obj = new MyHashMap(); - * obj->put(key,value); - * int param_2 = obj->get(key); - * obj->remove(key); - */ - -// option 2 use link list \ No newline at end of file diff --git a/C_plus/707*_DesignLinkedList.cpp b/C_plus/707*_DesignLinkedList.cpp deleted file mode 100644 index 90caddb..0000000 --- a/C_plus/707*_DesignLinkedList.cpp +++ /dev/null @@ -1,124 +0,0 @@ -class MyLinkedList -{ -public: - /** Initialize your data structure here. */ - struct Node - { - int val; - Node *next; - - Node() : val(0), next(nullptr) {} - Node(int x) : val(x), next(nullptr) {} - }; - - Node *first; - MyLinkedList() : first() {} - - /** Get the value of the index-th node in the linked list. If the index is invalid, return -1. */ - int get(int index) - { - Node *cur = first; - - while (index) - { - if (!cur->next) - return -1; - cur = cur->next; - index--; - } - return cur->val; - } - - /** Add a node of value val before the first element of the linked list. After the insertion, the new node will be the first node of the linked list. */ - void addAtHead(int val) - { - Node *node = new Node(val); - node->next = first; - first = node; - } - - /** Append a node of value val to the last element of the linked list. */ - void addAtTail(int val) - { - Node *node = new Node(val); - if (first == nullptr) - { - first = node; - return; - } - Node *cur = first; - while (cur->next) - { - cur = cur->next; - } - cur->next = node; - } - - /** Add a node of value val before the index-th node in the linked list. If index equals to the length of linked list, the node will be appended to the end of linked list. If index is greater than the length, the node will not be inserted. */ - void addAtIndex(int index, int val) - { - Node *node = new Node(val); - if (index == 0) - { - node->next = first; - first = node; - } - else - { - - Node *cur = first; - index--; - while (index) - { - if (!cur->next) - return; - cur = cur->next; - index--; - } - - node->next = cur->next; - cur->next = node; - } - } - - /** Delete the index-th node in the linked list, if the index is valid. */ - void deleteAtIndex(int index) - { - if (index == 0) - { - Node *delnode = first; - first = first->next; - delete delnode; - } - else - { - Node *cur = first; - index--; - while (index) - { - cur = cur->next; - index--; - } - if (index > 0) - return; - if (!cur->next || !cur->next->next) - { - cur->next = nullptr; - return; - } - Node *delnode = cur->next; - cur->next = cur->next->next; - delete delnode; - } - } -}; - -/** - * Your MyLinkedList object will be instantiated and called as such: - * MyLinkedList* obj = new MyLinkedList(); - * int param_1 = obj->get(index); - * obj->addAtHead(val); - * obj->addAtTail(val); - * obj->addAtIndex(index,val); - * obj->deleteAtIndex(index); - */ \ No newline at end of file diff --git a/C_plus/70_ClimbingStairs.cpp b/C_plus/70_ClimbingStairs.cpp deleted file mode 100644 index d979da8..0000000 --- a/C_plus/70_ClimbingStairs.cpp +++ /dev/null @@ -1,31 +0,0 @@ -class Solution -{ -public: - int climbStairs(int n) - { - // option 1 recurrent, time out O(2^n) time and O(n) space - // if(n <=3) return n; - // else return climbStairs(n-1) + climbStairs(n-2); - - // option 2 for-loop O(n) time - // if(n<=3) return n; - // int a = 1, b=2; - // int c = a+b; - // for(int i=4;i<=n;++i){ - // a = b; - // b = c; - // c =a+b; - // } - // return c; - - // option 3 dp - vector dp(n + 1, 1); - if (n <= 2) - return n; - for (int i = 2; i <= n; ++i) - { - dp[i] = dp[i - 1] + dp[i - 2]; - } - return dp[n]; - } -}; \ No newline at end of file diff --git a/C_plus/71*_SimplifyPath.cpp b/C_plus/71*_SimplifyPath.cpp deleted file mode 100644 index a0eeb5d..0000000 --- a/C_plus/71*_SimplifyPath.cpp +++ /dev/null @@ -1,38 +0,0 @@ -/* - * @Author: yuan - * @Date: 2021-05-12 20:27:58 - * @LastEditTime: 2021-05-12 20:27:58 - * @FilePath: /C_plus/71_SimplifyPath.cpp - */ -class Solution -{ -public: - string simplifyPath(string path) - { - string res, tmp; - vector stk; - stringstream ss(path); - while (getline(ss, tmp, '/')) - { - if (!tmp.empty()) - { - if (tmp == ".") - continue; - else if (tmp == "..") - { - if (!stk.empty()) - stk.pop_back(); - } - else - { - stk.push_back(tmp); - } - } - } - - for (string c : stk) - res += ('/' + c); - - return res.empty() ? "/" : res; - } -}; \ No newline at end of file diff --git a/C_plus/710*_RandomPickwithBlacklist.cpp b/C_plus/710*_RandomPickwithBlacklist.cpp deleted file mode 100644 index 46d48cb..0000000 --- a/C_plus/710*_RandomPickwithBlacklist.cpp +++ /dev/null @@ -1,69 +0,0 @@ -class Solution -{ -private: - // unordered_set black; - // int range ; - - unordered_map mapping; - int sz; - -public: - Solution(int n, vector &blacklist) - { - // option 1 time out - // black = unordered_set(blacklist.begin(), blacklist.end()); - // range = n; - - // option 2 大致上觀念就是把黑名單的數字映射到索引sz後,其他正常數字則沒事 - // (7, [2,3,5]) - // mapping 2->666 3->666 5->666 - - sz = n - blacklist.size(); - // 先將黑名單加入map - for (int b : blacklist) - { - // - mapping[b] = 666; - } - int last = n - 1; - // mapping 2->6 3->4 5->666 - for (int b : blacklist) - { - // 如果b已在區間 [sz, n),可以忽略 - if (b >= sz) - continue; - - // 跳過黑名單中的數字 - while (mapping.count(last)) - { - last--; - } - mapping[b] = last; - last--; - } - // 將黑名單的數字交換 區間 [sz,n) ,同時把 [0, sz) 中黑名單映射到正常數字 - } - - int pick() - { - // option 1 time out - // while(true){ - // int p = rand() % this->range; - // if(black.find(p) == black.end()) return p; - // } - - int index = rand() % sz; - // 如果索引命中黑名單,需要映射到其他位置 - if (mapping.count(index)) - return mapping[index]; - - // 若沒命中黑名單直接返回 - return index; - } -}; - -/** - * Your Solution object will be instantiated and called as such: - * Solution* obj = new Solution(n, blacklist); - * int param_1 = obj->pick(); - */ \ No newline at end of file diff --git a/C_plus/712*_MinimumASCIIDeleteSumforTwoStrings.cpp b/C_plus/712*_MinimumASCIIDeleteSumforTwoStrings.cpp deleted file mode 100644 index 19b95f4..0000000 --- a/C_plus/712*_MinimumASCIIDeleteSumforTwoStrings.cpp +++ /dev/null @@ -1,86 +0,0 @@ -class Solution -{ - -public: - int dp(string s1, int i, string s2, int j, vector > &memo) - { - int res = 0; - // base case - if (i == s1.size() || j == s2.size()) - { - if (i == s1.size()) - { - // s1到盡頭了,那s2剩下的都得刪除 - for (; j < s2.size(); ++j) - res += (int)s2[j]; - } - else if (j == s2.size()) - { - // s2到盡頭了,那s1剩下的都得刪除 - for (; i < s1.size(); ++i) - res += (int)s1[i]; - } - return res; - } - - if (memo[i][j] != -1) - return memo[i][j]; - - // s1[i] 、 s2[j] 都在最長子序列 - if (s1[i] == s2[j]) - return memo[i][j] = dp(s1, i + 1, s2, j + 1, memo); - else - { - // s1[i] s2[j] 至少一個不在LCS刪一個 - memo[i][j] = min( - (int)s1[i] + dp(s1, i + 1, s2, j, memo), - (int)s2[j] + dp(s1, i, s2, j + 1, memo)); - } - return memo[i][j]; - } - int minimumDeleteSum(string s1, string s2) - { - // 1143. Longest Common Subsequence LCS - // 583. Delete Operation for Two Strings - // option 1 memo time out - // 需要知道刪除的字符是什麼,無法直接用LCS,需要基於原先的LCS去修改。 - - // "sea" - // "eat" - // 231 332 429 - // 116 217 314 - // -1 116 213 - - // int n = s1.size(), m = s2.size(); - // vector> memo(n, vector(m,-1)); - // return dp(s1, 0, s2, 0, memo); - - // option 2 dp - // "sea" - // "eat" - // e a t = s2 - // 0 101 198 314 - // s 115 216 313 429 - // e 216 115 212 328 - // a 313 212 115 231 - int n = s1.size(), m = s2.size(); - vector > dp(n + 1, vector(m + 1, 0)); - - for (int i = 1; i <= n; ++i) - dp[i][0] = dp[i - 1][0] + s1[i - 1]; - for (int j = 1; j <= m; ++j) - dp[0][j] = dp[0][j - 1] + s2[j - 1]; - - for (int i = 1; i <= n; ++i) - { - for (int j = 1; j <= m; ++j) - { - if (s1[i - 1] == s2[j - 1]) - dp[i][j] = dp[i - 1][j - 1]; - else - dp[i][j] = min(dp[i - 1][j] + s1[i - 1], dp[i][j - 1] + s2[j - 1]); - } - } - return dp[n][m]; - } -}; \ No newline at end of file diff --git a/C_plus/713*_SubarrayProductLessThanK.cpp b/C_plus/713*_SubarrayProductLessThanK.cpp deleted file mode 100644 index cd97901..0000000 --- a/C_plus/713*_SubarrayProductLessThanK.cpp +++ /dev/null @@ -1,21 +0,0 @@ -class Solution -{ -public: - int numSubarrayProductLessThanK(vector &nums, int k) - { - // sliding window - int n = nums.size(); - int prod = 1, ret = 0; - int l = 0; - for (int r = 0; r < n; ++r) - { - prod *= nums[r]; - - while (l <= r && prod >= k) - prod /= nums[l++]; - - ret += (r - l + 1); - } - return ret; - } -}; \ No newline at end of file diff --git a/C_plus/714*_BestTimetoBuyandSellStockwithTransaction Fee.cpp b/C_plus/714*_BestTimetoBuyandSellStockwithTransaction Fee.cpp deleted file mode 100644 index 598d473..0000000 --- a/C_plus/714*_BestTimetoBuyandSellStockwithTransaction Fee.cpp +++ /dev/null @@ -1,42 +0,0 @@ -class Solution -{ -public: - int maxProfit(vector &prices, int fee) - { - // dp[i][0] = max(dp[i-1][0], dp[i-1][1] + prices[i]) - // dp[i][1] = max(dp[i-1][1], dp[i-1][0] - prices[i] - fee) - // 解释:相当于买入股票的价格升高了。 - // 在第一个式子里减也是一样的,相当于卖出股票的价格减小了。 - // 1 3 2 8 4 9 fee = 2 - - // dp[i][0] = max(dp[i-1][0] , dp[i-1][1] + prices[i] ); - // dp[i][1] = max(dp[i-1][1], dp[i-1][0] - prices[i] - fee); - // sell(0) hold(1) - //1 0 -3 - //3 0 -3 - //2 0 -3 - //8 5 -3 - //4 5 -1 - //9 8 -1 - - // int n = prices.size(); - // vector> dp(n ,vector(2,0)); - // dp[0][0] = 0; - // dp[0][1] = -prices[0]-fee; - // for(int i=1;i &bits) - { - // 兩種字符 第一種2-bit characters : 11 10,第二種1-bit character 0 - // 是否可以分割成 以1-bit結尾的 - - int n = bits.size(), i = 0; - while (i < n - 1) - { - if (bits[i] == 0) - i++; - else - i += 2; - } - return i == n - 1; - } -}; \ No newline at end of file diff --git a/C_plus/72*_EditDistance.cpp b/C_plus/72*_EditDistance.cpp deleted file mode 100644 index ecd49c1..0000000 --- a/C_plus/72*_EditDistance.cpp +++ /dev/null @@ -1,111 +0,0 @@ -class Solution -{ -public: - map, int> memo; - int distance(string s1, string s2, int i, int j) - { - - if (i == -1) - return j + 1; - if (j == -1) - return i + 1; - - if (memo.count(make_pair(i, j))) - return memo[make_pair(i, j)]; - - if (s1[i] == s2[j]) - { - memo[make_pair(i, j)] = distance(s1, s2, i - 1, j - 1); - return memo[make_pair(i, j)]; - } - - memo[make_pair(i, j)] = min(min( - distance(s1, s2, i - 1, j) + 1, // 刪除, - distance(s1, s2, i, j - 1) + 1 // 插入,相當於在 s1 後面插入 s2[j] ,插入後 j-- - - ), - distance(s1, s2, i - 1, j - 1) + 1 // 替換 - ); - return memo[make_pair(i, j)]; - } - - int dp(string s1, string s2, int i, int j) - { - //base case - if (i == -1) - return j + 1; - if (j == -1) - return i + 1; - - if (s1[i] == s2[j]) - return dp(s1, s2, i - 1, j - 1); // 往前走 - else - { - return Getmin( - dp(s1, s2, i, j - 1) + 1, // 插入 - dp(s1, s2, i - 1, j) + 1, // 刪除 - dp(s1, s2, i - 1, j - 1) + 1 // 替換 - ); - } - } - int Getmin(int a, int b, int c) - { - return min(a, min(b, c)); - } - int minDistance(string word1, string word2) - { - // option 1 dp brute force -> time out - // 三種操作 替代、刪除、插入 - // 雙指標從字串尾部開始遍歷,遇到字符相同,就什麼都別做skip,i--,j-- - // if s1[i] == s2[j]: - // 啥都别做(skip) - // i, j 同时向前移动 - // 三種操作都是用遞迴遍歷尋找最小編輯距離 - // else: - // 三选一: - // 插入(insert) - // 删除(delete) - // 替换(replace) - - // - // return dp(word1, word2, word1.size()-1, word2.size()-1); - - // option 2 memo 避免重疊子問題 - return distance(word1, word2, word1.size() - 1, word2.size() - 1); - // s1[i-1] !=s2[j-1] , dp[i][j] = min(insert, delete, replace) - // s1[i-1] !=s2[j-1] , dp[i][j] = min(dp[i][j-1] +1 , dp[i-1][j]+1, dp[i-1][j-1]) - // s1[i] == s2[j] , dp[i][j] = dp[i-1][j-1] - // option 3 dp - //dp - // h o r s e - // 0 1 2 3 4 5 - //r 1 1 2 2 3 4 - //o 2 2 1 2 3 4 - //s 3 3 2 2 2 3 - - // 替換/跳過 刪除 - // 插入 現在狀態 - // dp[i][j] = dp[i-1][j-1] - // dp[i][j] = min( dp[i-1][j-1], dp[i-1][j], dp[i][j-1]); - - int m = word1.size(), n = word2.size(); - vector > dp(m + 1, vector(n + 1, 0)); - for (int i = 0; i <= m; ++i) - dp[i][0] = i; - for (int j = 0; j <= n; ++j) - dp[0][j] = j; - - for (int i = 1; i <= m; ++i) - { - for (int j = 1; j <= n; ++j) - { - if (word1[i - 1] == word2[j - 1]) - dp[i][j] = dp[i - 1][j - 1]; - else - dp[i][j] = min( - dp[i - 1][j] + 1, min(dp[i - 1][j - 1] + 1, dp[i][j - 1] + 1)); - } - } - return dp[m][n]; - } -}; \ No newline at end of file diff --git a/C_plus/725*_SplitLinkedListinParts.cpp b/C_plus/725*_SplitLinkedListinParts.cpp deleted file mode 100644 index 24f8181..0000000 --- a/C_plus/725*_SplitLinkedListinParts.cpp +++ /dev/null @@ -1,35 +0,0 @@ -/** - * Definition for singly-linked list. - * struct ListNode { - * int val; - * ListNode *next; - * ListNode() : val(0), next(nullptr) {} - * ListNode(int x) : val(x), next(nullptr) {} - * ListNode(int x, ListNode *next) : val(x), next(next) {} - * }; - */ -class Solution -{ -public: - vector splitListToParts(ListNode *head, int k) - { - vector ret(k, nullptr); - int len = 0; - for (ListNode *p = head; p; p = p->next) - len++; - int r = len % k, p = len / k; - - ListNode *node = head, *prev = nullptr; - for (int i = 0; node && i < k; i++, r--) - { - ret[i] = node; - for (int j = 0; j < p + (r > 0); j++) - { - prev = node; - node = node->next; - } - prev->next = nullptr; - } - return ret; - } -}; \ No newline at end of file diff --git a/C_plus/733_FloodFill.cpp b/C_plus/733_FloodFill.cpp deleted file mode 100644 index 1c33143..0000000 --- a/C_plus/733_FloodFill.cpp +++ /dev/null @@ -1,29 +0,0 @@ -class Solution -{ -public: - void flood(int i, int j, int color, int newColor, vector > &ret) - { - if (i < 0 || j < 0 || i > ret.size() - 1 || j > ret[0].size() - 1 || ret[i][j] != color) - return; - ret[i][j] = newColor; - - flood(i - 1, j, color, newColor, ret); - - flood(i + 1, j, color, newColor, ret); - flood(i, j - 1, color, newColor, ret); - flood(i, j + 1, color, newColor, ret); - } - vector > floodFill(vector > &image, int sr, int sc, int newColor) - { - - // option 1 DFS - if (image[sr][sc] == newColor) - return image; - int m = image.size(), n = image[0].size(); - vector > ret = image; - - flood(sr, sc, image[sr][sc], newColor, ret); - - return ret; - } -}; \ No newline at end of file diff --git a/C_plus/739*_DailyTemperatures.cpp b/C_plus/739*_DailyTemperatures.cpp deleted file mode 100644 index 681bf1c..0000000 --- a/C_plus/739*_DailyTemperatures.cpp +++ /dev/null @@ -1,41 +0,0 @@ -class Solution -{ -public: - vector dailyTemperatures(vector &temperatures) - { - // option 1 順向 monotonic stack - stack sta; - int size = temperatures.size(); - vector ret(size, 0); - for (int i = 0; i < size; ++i) - { - while (!sta.empty() && temperatures[i] > temperatures[sta.top()]) - { - int t = sta.top(); - sta.pop(); - ret[t] = i - t; - } - sta.push(i); - } - return ret; - - //option 2 monotonic stack - int size = temperatures.size(); - // 放元素索引 - vector ret(size); - stack sta; - - for(int i=size-1 ;i>-1;i--){ - - while(!sta.empty() && temperatures[sta.top()] <= temperatures[i]){ - sta.pop(); - } - // 索引差距 - ret[i] = sta.empty()? 0 : (sta.top()-i); - sta.push(i); - - } - return ret; - - } -}; \ No newline at end of file diff --git a/C_plus/73_SetMatrixZeroes.cpp b/C_plus/73_SetMatrixZeroes.cpp deleted file mode 100644 index 63f988d..0000000 --- a/C_plus/73_SetMatrixZeroes.cpp +++ /dev/null @@ -1,95 +0,0 @@ -class Solution -{ -public: - void setZeroes(vector > &matrix) - { - // option 1 O(n*m) space - // int m = matrix.size(), n = matrix[0].size(); - // vector> coor; - // for(int i = 0;i p:coor){ - // for(int j=0;j &cost) - { - // 10 15 20 => 10 10 10 15=min(10+20,15) - // 1 100 1 1 1 100 1 1 100 1 - // 0 0 1 2 3 3 3 4 4 5 6 - - int size = cost.size(); - if (size < 3) - min(cost[0], cost[1]); - vector dp(size + 1, 999); - dp[0] = 0; - dp[1] = 0; - for (int i = 2; i <= size; ++i) - { - dp[i] = min(cost[i - 1] + dp[i - 1], cost[i - 2] + dp[i - 2]); - } - return dp[size]; - } -}; \ No newline at end of file diff --git a/C_plus/74_Searcha2DMatrix.cpp b/C_plus/74_Searcha2DMatrix.cpp deleted file mode 100644 index ce233ed..0000000 --- a/C_plus/74_Searcha2DMatrix.cpp +++ /dev/null @@ -1,51 +0,0 @@ -class Solution -{ -public: - bool searchMatrix(vector > &matrix, int target) - { - - // option 1 - // binary search - if (matrix.empty() || matrix[0].empty()) - return false; - - // 找哪一行第一個元素第一個大於等於target的行數 - int l = 0, r = matrix.size(); - while (l < r) - { - int mid = l + (r - l) / 2; - if (matrix[mid][0] == target) - return true; - else if (matrix[mid][0] < target) - l = mid + 1; - else if (matrix[mid][0] > target) - r = mid; - } - - int tmp = (r > 0) ? (r - 1) : r; - l = 0; - r = matrix[tmp].size(); - while (l < r) - { - int mid = l + (r - l) / 2; - - if (matrix[tmp][mid] == target) - return true; - else if (matrix[tmp][mid] < target) - l = mid + 1; - else - r = mid; - } - return false; - - // option 2 - // int m = matrix.size(), n= matrix[0].size(); - // int i = m-1, j=0; - // while( i >=0 && j<=n-1){ - // if(target ==matrix[i][j]) return true; - // if(target > matrix[i][j]) j++; - // else i--; - // } - // return false; - } -}; \ No newline at end of file diff --git a/C_plus/752*_OpentheLock.cpp b/C_plus/752*_OpentheLock.cpp deleted file mode 100644 index 2ef535c..0000000 --- a/C_plus/752*_OpentheLock.cpp +++ /dev/null @@ -1,105 +0,0 @@ -class Solution -{ -public: - string plusOne(string s, int j) - { - - if (s[j] == '9') - s[j] = '0'; - else - s[j] = s[j] += 1; - return s; - } - string minusOne(string s, int j) - { - if (s[j] == '0') - s[j] = '9'; - else - s[j] = s[j] -= 1; - return s; - } - - int openLock(vector &deadends, string target) - { - // option BFS - // 用集合代替,可減少搜尋時間 - // set deads ; - // for(string d:deadends) deads.insert(d); - // queue q; - // q.push("0000"); - // int step = 0; - // set visited; - // visited.insert("0000"); - // while(!q.empty()){ - // int size = q.size(); - - // for(int i=0;i deads, visited, q1, q2; - for (string d : deadends) - deads.insert(d); - q1.insert("0000"); - q2.insert(target); - visited.insert("0000"); - int step = 0; - - while (!q1.empty() && !q2.empty()) - { - set temp; - - for (string cur : q1) - { - if (deads.count(cur)) - continue; - if (q2.find(cur) != q2.end()) - return step; - - visited.insert(cur); - for (int j = 0; j < 4; ++j) - { - string up = plusOne(cur, j); - string down = minusOne(cur, j); - if (visited.find(up) == visited.end()) - { - temp.insert(up); - } - if (visited.find(down) == visited.end()) - { - temp.insert(down); - } - } - } - step++; - q1 = q2; - q2 = temp; - } - return -1; - } -}; \ No newline at end of file diff --git a/C_plus/75_SetColor.cpp b/C_plus/75_SetColor.cpp deleted file mode 100644 index 3ed90b0..0000000 --- a/C_plus/75_SetColor.cpp +++ /dev/null @@ -1,46 +0,0 @@ -class Solution -{ -public: - void sortColors(vector &nums) - { - - // option 1 insert sort - // for(int i =1;i=0 && key<=nums[j]){ - // nums[j+1] = nums[j]; - // j--; - // } - // nums[j+1]=key; - - // } - - // option 2 create vector to record - // option cheap O(n) - vector his(3, 0); - for (int n : nums) - his[n]++; - for (int i = 0, j = 0; i < nums.size(); ++i) - { - while (his[j] == 0) j++; - his[j]--; - nums[i] = j; - } - - // option 3 two pointer - int n = nums.size(); - int red = 0, blue = n - 1; - for (int i = 0; i <= blue; ++i) - { - if (nums[i] == 0) - { - swap(nums[i], nums[red++]); - } - else if (nums[i] == 2) - { - swap(nums[i--], nums[blue--]); - } - } - } -}; \ No newline at end of file diff --git a/C_plus/76*_MinimumWindowSubstring.cpp b/C_plus/76*_MinimumWindowSubstring.cpp deleted file mode 100644 index 42e733d..0000000 --- a/C_plus/76*_MinimumWindowSubstring.cpp +++ /dev/null @@ -1,112 +0,0 @@ -class Solution { -public: - string minWindow(string s, string t) { - // option 1 滑動窗口框架 O(N) time -// int left = 0, right = 0; - -// while (right < s.size()) {` -// // 增大窗口 -// window.add(s[right]); -// right++; - -// while (window needs shrink) { -// // 缩小窗口 -// window.remove(s[left]); -// left++; -// } -// } - - /* 滑动窗口算法框架 */ -// void slidingWindow(string s, string t) { -// unordered_map need, window; -// for (char c : t) need[c]++; - -// int left = 0, right = 0; -// int valid = 0; -// while (right < s.size()) { -// // c 是将移入窗口的字符 -// char c = s[right]; -// // 右移窗口 -// right++; -// // 进行窗口内数据的一系列更新 -// ... - -// /*** debug 输出的位置 ***/ -// printf("window: [%d, %d)\n", left, right); -// /********************/ - -// // 判断左侧窗口是否要收缩 -// while (window needs shrink) { -// // d 是将移出窗口的字符 -// char d = s[left]; -// // 左移窗口 -// left++; -// // 进行窗口内数据的一系列更新 -// ... -// } -// } -// } - - - // option 1 brute force - // O(n^4) must be timeout -// if(s.size() < t.size()) return ""; -// string ret=""; -// for(int i=0;i temp.size()) ret = temp; -// } - -// } -// } - -// return ret; - // option 2 slide window O(N) time - - // 因為結果不論順序與否,只要包含即可,所以用hash - // window 是左閉區間右開區間。 - unordered_map need, window; - for(char c:t) need[c]++; - int valid = 0; - int left = 0, right = 0; - int start = 0, len = INT_MAX; - while(right primes(right+1, true); - // primes[0] = false, primes[1] = false; - // for(int i = 2;i<=right ;++i){ - // if(primes[i]){ - // for(int j = i+i;j primes = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29}; - for (int i = left; i <= right; ++i) - { - int k = count(i); - // int k = __builtin_popcount(i); - if (primes.count(k)) - ret++; - } - return ret; - } -}; \ No newline at end of file diff --git a/C_plus/77*_Combinations.cpp b/C_plus/77*_Combinations.cpp deleted file mode 100644 index 63ee97b..0000000 --- a/C_plus/77*_Combinations.cpp +++ /dev/null @@ -1,33 +0,0 @@ -class Solution -{ -public: - void backtrack(int n, int k, int start, vector &track, vector > &ret) - { - - // 到達樹的底部 - if (k == track.size()) - { - ret.push_back(track); - return; - } - - for (int i = start; i <= n; ++i) - { - // 做選擇 - track.push_back(i); - // 進入下一層決策樹 - backtrack(n, k, i + 1, track, ret); - // 撤消選擇 - track.pop_back(); - } - } - vector > combine(int n, int k) - { - vector > ret; - if (k <= 0 || n <= 0) - return ret; - vector track; - backtrack(n, k, 1, track, ret); - return ret; - } -}; \ No newline at end of file diff --git a/C_plus/771_JewelsAndStones.cpp b/C_plus/771_JewelsAndStones.cpp deleted file mode 100644 index 50b276d..0000000 --- a/C_plus/771_JewelsAndStones.cpp +++ /dev/null @@ -1,25 +0,0 @@ -class Solution -{ -public: - int numJewelsInStones(string jewels, string stones) - { - // option 1 O( nlogn) - // set s(jewels.begin(), jewels.end()); - - // int ret = 0; - // for(char c:stones){ - // if(s.find(c)!=s.end()) ret++; - // } - - // return ret; - - // option 2 O(n) - vector v(128, 0); - for (char c : stones) - v[c]++; - int ret = 0; - for (char c : jewels) - ret += v[c]; - return ret; - } -}; \ No newline at end of file diff --git a/C_plus/773*_SlidingPuzzle.cpp b/C_plus/773*_SlidingPuzzle.cpp deleted file mode 100644 index eec4824..0000000 --- a/C_plus/773*_SlidingPuzzle.cpp +++ /dev/null @@ -1,59 +0,0 @@ -class Solution -{ -public: - int slidingPuzzle(vector > &board) - { - // [[1,2,3],[4,0,5] ] = 1 2 3 4 0 5 - int m = 2, n = 3; - string start = ""; - string target = "123450"; - for (int i = 0; i < m; ++i) - { - for (int j = 0; j < n; ++j) - { - start.push_back(board[i][j] + '0'); - } - } - // start = [1,2,3,4,0,5] - // 紀錄每個index 鄰居的index - vector > neighbor = {{1, 3}, {0, 2, 4}, {1, 5}, {0, 4}, {1, 3, 5}, {2, 4}}; - - // BFS - queue q; - unordered_set visited; - q.push(start); - visited.insert(start); - int step = 0; - while (!q.empty()) - { - int size = q.size(); - for (int i = 0; i < size; ++i) - { - string cur = q.front(); - q.pop(); - - if (target == cur) - return step; - - int idx = 0; - // 找數字0的索引 - for (; cur[idx] != '0'; ++idx) - ; - for (int adj : neighbor[idx]) - { - string new_board = cur; - - swap(new_board[adj], new_board[idx]); - if (!visited.count(new_board)) - { - q.push(new_board); - visited.insert(new_board); - } - } - } - step++; - } - - return -1; - } -}; \ No newline at end of file diff --git a/C_plus/78*_Subsets.cpp b/C_plus/78*_Subsets.cpp deleted file mode 100644 index 6d78112..0000000 --- a/C_plus/78*_Subsets.cpp +++ /dev/null @@ -1,69 +0,0 @@ -class Solution -{ -public: - void backtrack(vector &nums, int start, vector &track, vector > &ret) - { - // 對ret 的更新其實是 preorder - ret.push_back(track); - for (int i = start; i < nums.size(); ++i) - { - // 做選擇 - track.push_back(nums[i]); - // 回朔 - backtrack(nums, i + 1, track, ret); - // 撤消選擇 - track.pop_back(); - } - } - - vector > subsets(vector &nums) - { - - // option 1 Recursion - // O(N * 2^N) time and O(N *2^N) space 包含 O(N) recursive function call stack - // subsets([1,2,3]) = subset([1,2]) + [s.append(3) for s in subset([1,2]) ] - // base case - if (nums.empty()) - return {{}}; - // 把最後一個元素拿出來 - int n = nums.back(); - nums.pop_back(); - - vector > ret = subsets(nums); - - int size = ret.size(); - for (int i = 0; i < size; ++i) - { - // 在之前的結果中追加 - ret.push_back(ret[i]); - ret.back().push_back(n); - } - return ret; - - // option 2 DFS - vector > ret; - vector track; - backtrack(nums, 0, track, ret); - return ret; - - // option 3 iterative - // vector > ret; - // ret.push_back({}); - // for (int n : nums) - // { - // int s = ret.size(); - // for (int j = 0; j < s; ++j) - // { - // 1. 先新增變數儲存要增加到ret尾部的vector 2. 再將vector尾部加n 3. 將vector加入ret尾部 - // vector tmp = ret[j]; - // tmp.push_back(n); - // ret.push_back(tmp); - - // 1. ret尾部複製一份索引j的vector,再將其vector尾部加n - // ret.push_back(ret[j]); - // ret.back().push_back(n); - // } - // } - // return ret; - } -}; \ No newline at end of file diff --git a/C_plus/783_MinimumDistanceBetweenBSTNodes.cpp b/C_plus/783_MinimumDistanceBetweenBSTNodes.cpp deleted file mode 100644 index 656e78b..0000000 --- a/C_plus/783_MinimumDistanceBetweenBSTNodes.cpp +++ /dev/null @@ -1,42 +0,0 @@ -/* - * @Author: yuan - * @Date: 2021-07-16 16:27:24 - * @LastEditTime: 2021-07-16 16:27:24 - * @FilePath: /leet_code/C_plus/783_MinimumDistanceBetweenBSTNodes.cpp - */ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution -{ -public: - void preorder(TreeNode *root, vector &vec) - { - if (root == nullptr) - return; - preorder(root->left, vec); - vec.push_back(root->val); - preorder(root->right, vec); - } - - int minDiffInBST(TreeNode *root) - { - vector vec; - int ret = 100001; - preorder(root, vec); - for (int i = 1; i < vec.size(); ++i) - { - int diff = abs(vec[i] - vec[i - 1]); - ret = min(diff, ret); - } - return ret; - } -}; \ No newline at end of file diff --git a/C_plus/784_LetterCasePermutation.cpp b/C_plus/784_LetterCasePermutation.cpp deleted file mode 100644 index 519bcd5..0000000 --- a/C_plus/784_LetterCasePermutation.cpp +++ /dev/null @@ -1,44 +0,0 @@ -class Solution -{ -public: - vector ret; - void traverse(string &s, string &path, int l) - { - - if (path.size() == s.size()) - { - ret.push_back(path); - } - // if(l>= s.size()) reutrn; - - for (int i = l; i < s.size(); ++i) - { - // 因為只會有大小寫與數字 - if (s[i] >= '0' && s[i] <= '9') - { - path.push_back(s[i]); - traverse(s, path, i + 1); - path.pop_back(); - } - // if(( s[i]>='a' && s[i]<='z') || (s[i]>='A' && s[i]<='Z')){ - else - { - // 選擇小寫 - path.push_back(tolower(s[i])); - traverse(s, path, i + 1); - path.pop_back(); - - // 選擇大寫 - path.push_back(toupper(s[i])); - traverse(s, path, i + 1); - path.pop_back(); - } - } - } - vector letterCasePermutation(string s) - { - string path; - traverse(s, path, 0); - return ret; - } -}; \ No newline at end of file diff --git a/C_plus/787*_CheapestFlightsWithinKStops.cpp b/C_plus/787*_CheapestFlightsWithinKStops.cpp deleted file mode 100644 index 3ec7608..0000000 --- a/C_plus/787*_CheapestFlightsWithinKStops.cpp +++ /dev/null @@ -1,59 +0,0 @@ -class Solution -{ -public: - unordered_map > > indegree; - vector > memo; - int src, dst; - int dp(int s, int k) - { - // 定義:從s出發,k步類到達s的最小成本 - if (s == src) - return 0; - // 步數用盡 - if (k == 0) - return -1; - int ret = INT_MAX; - - // 查看備忘錄 - if (memo[s][k] != -888) - return memo[s][k]; - - if (indegree.count(s)) - { - - for (auto v : indegree[s]) - { - int from = v[0]; - int price = v[1]; - - int subProblem = dp(from, k - 1); - if (subProblem != -1) - { - ret = min(ret, subProblem + price); - } - } - } - memo[s][k] = ret == INT_MAX ? -1 : ret; - return memo[s][k]; - } - int findCheapestPrice(int n, vector > &flights, int src, int dst, int k) - { - - this->src = src; - this->dst = dst; - k++; - // 初始備忘錄 - memo = vector >(n, vector(k + 1, -888)); - - for (vector f : flights) - { - int from = f[0]; - int to = f[1]; - int price = f[2]; - - indegree[to].push_back({from, price}); - } - - return dp(dst, k); - } -}; \ No newline at end of file diff --git a/C_plus/79*_WordSearch.cpp b/C_plus/79*_WordSearch.cpp deleted file mode 100644 index 9cde6bb..0000000 --- a/C_plus/79*_WordSearch.cpp +++ /dev/null @@ -1,33 +0,0 @@ -class Solution -{ -public: - bool exist(vector > &board, string word) - { - // DFS - int m = board.size(), n = board[0].size(); - vector > visited(m, vector(n, false)); - for (int i = 0; i < m; ++i) - { - for (int j = 0; j < n; ++j) - { - if (search(board, word, 0, i, j, visited)) - return true; - } - } - return false; - } - bool search(vector > &board, string word, int idx, int i, int j, vector > &visited) - { - if (idx == word.size()) - return true; - - int m = board.size(), n = board[0].size(); - if (i < 0 || j < 0 || i >= m || j >= n || visited[i][j] || board[i][j] != word[idx]) - return false; - visited[i][j] = true; - bool res = search(board, word, idx + 1, i - 1, j, visited) || search(board, word, idx + 1, i + 1, j, visited) || search(board, word, idx + 1, i, j - 1, visited) || search(board, word, idx + 1, i, j + 1, visited); - - visited[i][j] = false; - return res; - } -}; \ No newline at end of file diff --git a/C_plus/791_CustomSortString.cpp b/C_plus/791_CustomSortString.cpp deleted file mode 100644 index 4e300d3..0000000 --- a/C_plus/791_CustomSortString.cpp +++ /dev/null @@ -1,29 +0,0 @@ -/* - * @Author: yuan - * @Date: 2021-07-14 17:39:02 - * @LastEditTime: 2021-07-14 17:39:03 - * @FilePath: /leet_code/C_plus/791_CustomSortString.cpp - */ -class Solution { -public: - string customSortString(string order, string str) { - vector vec(order.begin(), order.end()); - - map mp; - for(char c: str) mp[c]++; - string ret="", tail=""; - for(char c:vec){ - if(mp.count(c)){ - - ret.append(mp[c], c); - } - } - for(char c: str){ - vector::iterator it =std::find(vec.begin(), vec.end(), c); - - if(it==vec.end()) ret +=c; - } - cout< 0 - // input 5~9 => 1 - // input 10~14 => 2 - // input 15~19 => 3 - - if (n == 0) - return 0; - long ret = 0; - for (long d = n; d / 5 > 0; d /= 5) - { - ret += d / 5; - } - return ret; - } - int preimageSizeFZF(int k) - { - - // option 1 - // brute force 果然 timeout - // int ret = 0; - // for(int i =0;i<=1e+9 ;++i){ - // int eval = trailingZeroes(i); - // if(eval > k) break; - // if(eval == k) ret++; - // // if(eval < k) continue; - // } - // return ret; - - // binary search O(logK) - // 有多少數字的階層後面有k 個0 - // 因為單調trailingZeroes是遞增函數,那答案就相當於求 - // 二元搜尋右側邊界 - 二元搜尋右側邊界 +1 - return right_bound(k) - lower_bound(k) + 1; - } - int lower_bound(int k) - { - long l = 0, r = LONG_MAX; - while (l < r) - { - long mid = l + (r - l) / 2; // avoid overflow - long eval = trailingZeroes(mid); - - if (eval == k) - r = mid; - else if (eval > k) - r = mid; - else if (eval < k) - l = mid + 1; - } - return l; - } - int right_bound(int k) - { - long l = 0, r = LONG_MAX; - while (l < r) - { - long mid = l + (r - l) / 2; // avoid overflow - long eval = trailingZeroes(mid); - - if (eval == k) - l = mid + 1; - else if (eval > k) - r = mid; - else if (eval < k) - l = mid + 1; - } - return l - 1; - } -}; \ No newline at end of file diff --git a/C_plus/796_RotateString.cpp b/C_plus/796_RotateString.cpp deleted file mode 100644 index c614352..0000000 --- a/C_plus/796_RotateString.cpp +++ /dev/null @@ -1,27 +0,0 @@ -class Solution -{ -public: - bool rotateString(string s, string goal) - { - // option 1 O(len a + len b) - // 將字串s1 = s1+s1 在判斷s2是否為s1子字串 - if (s.empty() && goal.empty()) - return true; - int a = s.size(); - s = s + s; - if (a > 0 && a == goal.size()) - { - if (s.find(goal) != std::string::npos) - return true; - } - return false; - - // option 1.1 improved - if (s.size() != goal.size()) - return false; - s = s + s; - return (s.find(goal) != std::string::npos); - } -} -} -; \ No newline at end of file diff --git a/C_plus/797*_AllPathsFromSourcetoTarget.cpp b/C_plus/797*_AllPathsFromSourcetoTarget.cpp deleted file mode 100644 index 1d72a52..0000000 --- a/C_plus/797*_AllPathsFromSourcetoTarget.cpp +++ /dev/null @@ -1,60 +0,0 @@ -class Solution -{ -public: - void traverse(vector > &graph, int pos, vector path, vector > &ret) - { - // DFS traverse - int n = graph.size(); - // DFS - // 添加節點s 到路徑 - path.push_back(pos); - if (path.back() == n - 1) - { - // if(pos == n-1){ // 到達終點 - ret.push_back(path); - path.pop_back(); - return; - } - - // 遍歷每個相鄰節點 - for (int p : graph[pos]) - { - traverse(graph, p, path, ret); - } - // 從路徑移出節點 - path.pop_back(); - } - vector > allPathsSourceTarget(vector > &graph) - { - vector > ret; - vector path; - traverse(graph, 0, path, ret); - return ret; - - // BFS - int n = graph.size()-1; - vector> ret; - queue> q; - q.push({0}); - int len=1; - while(!q.empty()){ - - int size = q.size(); - for(int i=0;i path = q.front(); - q.pop(); - if(path.back() == n) { - ret.push_back(path); - } - - for(int pos:graph[path.back()]){ - vector tmp = path; - tmp.push_back(pos); - q.push(tmp); - } - } - len++; - } - return ret; - } -}; \ No newline at end of file diff --git a/C_plus/7_ReverseInteger.cpp b/C_plus/7_ReverseInteger.cpp deleted file mode 100644 index dfeff6d..0000000 --- a/C_plus/7_ReverseInteger.cpp +++ /dev/null @@ -1,17 +0,0 @@ -class Solution -{ -public: - int reverse(int x) - { - int ret = 0; - while (x) - { - if (abs(ret) > INT_MAX / 10) - return 0; - ret *= 10; - ret += x % 10; - x /= 10; - } - return ret; - } -}; \ No newline at end of file diff --git a/C_plus/80*_RemoveDuplicatesfromSortedArrayII.cpp b/C_plus/80*_RemoveDuplicatesfromSortedArrayII.cpp deleted file mode 100644 index 933207d..0000000 --- a/C_plus/80*_RemoveDuplicatesfromSortedArrayII.cpp +++ /dev/null @@ -1,26 +0,0 @@ -class Solution -{ -public: - int removeDuplicates(vector &nums) - { - if (nums.empty()) - return 0; - int slow = 0, count = 1, fast = 1; - while (fast < nums.size()) - { - - if (nums[fast] == nums[slow] && count == 0) - fast++; - else - { - if (nums[fast] == nums[slow]) - count--; - else - count = 1; - - nums[++slow] = nums[fast++]; - } - } - return slow + 1; - } -}; \ No newline at end of file diff --git a/C_plus/81*_SearchinRotatedSortedArrayII.cpp b/C_plus/81*_SearchinRotatedSortedArrayII.cpp deleted file mode 100644 index c01659f..0000000 --- a/C_plus/81*_SearchinRotatedSortedArrayII.cpp +++ /dev/null @@ -1,84 +0,0 @@ -class Solution -{ -public: - bool search(vector &nums, int target) - { - - // option 1 - // 1. 先復原O(nlogn) - // 2. binary search - - // int peek = 0; - // for(int i=1;i nums[l]){ - if(target >= nums[l] && target<= nums[mid]) r = mid-1; - else l = mid +1; - - } - else if(nums[mid] < nums[r]){ - if(target >= nums[mid] && target <= nums[r]) l = mid+1; - else r = mid-1; - } - else l++; - - } - - return false; - - // option 3 - // binary search O(logn) - int n = nums.size(); - int l = 0, r = n - 1; - while (l <= r) - { - int mid = l + (r - l) / 2; - if (nums[mid] == target) - return true; - if (nums[r] > nums[mid]) - { - // 右半部遞增 - if (target <= nums[r] && target > nums[mid]) - l = mid + 1; - else - r = mid; - } - else if (nums[r] < nums[mid]) - { - if (target < nums[mid] && target >= nums[l]) - r = mid; - else - l = mid + 1; - } - else - r--; - } - return false; - } -}; \ No newline at end of file diff --git a/C_plus/814*_BinaryTreePruning.cpp b/C_plus/814*_BinaryTreePruning.cpp deleted file mode 100644 index b3f2944..0000000 --- a/C_plus/814*_BinaryTreePruning.cpp +++ /dev/null @@ -1,23 +0,0 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution -{ -public: - TreeNode *pruneTree(TreeNode *root) - { - if (!root) - return nullptr; - root->left = pruneTree(root->left); - root->right = pruneTree(root->right); - return (!root->left && !root->right && root->val == 0) ? nullptr : root; - } -}; \ No newline at end of file diff --git a/C_plus/817*_LInkedListComponents.cpp b/C_plus/817*_LInkedListComponents.cpp deleted file mode 100644 index b5f8df7..0000000 --- a/C_plus/817*_LInkedListComponents.cpp +++ /dev/null @@ -1,36 +0,0 @@ -/** - * Definition for singly-linked list. - * struct ListNode { - * int val; - * ListNode *next; - * ListNode() : val(0), next(nullptr) {} - * ListNode(int x) : val(x), next(nullptr) {} - * ListNode(int x, ListNode *next) : val(x), next(next) {} - * }; - */ -class Solution -{ -public: - int numComponents(ListNode *head, vector &nums) - { - unordered_set nodeset(nums.begin(), nums.end()); - int ret = 0; - while (head) - { - if (!nodeset.count(head->val)) - { // not find head node in the nodeset - head = head->next; - continue; - } - else - { - while (head && nodeset.count(head->val)) - { // find head node in the nodeset - head = head->next; - } - ret++; - } - } - return ret; - } -}; \ No newline at end of file diff --git a/C_plus/82_RemoveDuplicatesfromSortedListII.cpp b/C_plus/82_RemoveDuplicatesfromSortedListII.cpp deleted file mode 100644 index f006792..0000000 --- a/C_plus/82_RemoveDuplicatesfromSortedListII.cpp +++ /dev/null @@ -1,58 +0,0 @@ -/** - * Definition for singly-linked list. - * struct ListNode { - * int val; - * ListNode *next; - * ListNode() : val(0), next(nullptr) {} - * ListNode(int x) : val(x), next(nullptr) {} - * ListNode(int x, ListNode *next) : val(x), next(next) {} - * }; - */ -class Solution -{ -public: - ListNode *deleteDuplicates(ListNode *head) - { - // option 1 O(nlogn) time O(s) space - // 1. 儲存重複節點的值 - // 2. 建立一個新的list 比較是否重複節點,不是則加入新串列 - // if(!head) return head; - // ListNode *ret = new ListNode(-101); - // set s; - // ListNode *p = head; - // while(p->next){ - // if(p->val ==p->next->val) s.insert(p->val); - // p=p->next; - // } - // p=ret; - // ListNode *cur = head; - // while(cur){ - // if(s.find(cur->val)==s.end() ) { - // p->next = new ListNode(cur->val); - // p=p->next; - - // } - // cur=cur->next; - // } - // return ret->next; - - // option 2 O(n^2) time O(1) space - if (!head || !head->next) - return head; - ListNode *ret = new ListNode(-1), *p = ret; - ret->next = head; - while (p->next) - { - ListNode *run = p->next; - while (run->next && run->next->val == run->val) - { - run = run->next; - } - if (run == p->next) - p = p->next; - else - p->next = run->next; - } - return ret->next; - } -}; \ No newline at end of file diff --git a/C_plus/836*_RectangleOverlap.cpp b/C_plus/836*_RectangleOverlap.cpp deleted file mode 100644 index 8d712d8..0000000 --- a/C_plus/836*_RectangleOverlap.cpp +++ /dev/null @@ -1,11 +0,0 @@ -class Solution { -public: - bool isRectangleOverlap(vector& rec1, vector& rec2) { - // 加等號 是因為To be clear, two rectangles that only touch at the corner or edges do not overlap. - if(rec1[2] <= rec2[0] ) return false; - if(rec1[0] >= rec2[2]) return false; - if(rec1[1] >= rec2[3] ) return false; - if(rec1[3] <= rec2[1]) return false; - return true; - } -}; \ No newline at end of file diff --git a/C_plus/838*_PushDominoes.cpp b/C_plus/838*_PushDominoes.cpp deleted file mode 100644 index 8fa4904..0000000 --- a/C_plus/838*_PushDominoes.cpp +++ /dev/null @@ -1,40 +0,0 @@ -class Solution -{ -public: - string pushDominoes(string dominoes) - { - // https://www.cnblogs.com/grandyang/p/10393508.html - // 分為四種情況 - // 情況一 R...R => RRRRR , 骨牌往右倒 - // 情況二 L...L => LLLLL , 骨牌往左倒 - // 情況三 L...R => L...R , 中間骨牌不受力 - // 情況四 R...L => RRRLLL or RRR.LLL , 要看中間骨牌個數,如果是偶數,那對半,若是奇數,那最中間股台保持站立,其餘對半分 - - // 所以只要者出最中間的“.”的小區間,使用雙指針遍歷。 - string res = ""; - // j指向“.” 則跳過,目標是i指向小區間的左邊界,j指向右邊界,j-i-1則是中間"點"的個數。 - // 若 i > 0< - dominoes = "L" + dominoes + "R"; - for (int i = 0, j = 1; j < dominoes.size(); ++j) - { - if (dominoes[j] == '.') - continue; - int mid = j - i - 1; - // 情況二 - if (i > 0) - res += dominoes[i]; - // 情況一 - if (dominoes[i] == dominoes[j]) - res += string(mid, dominoes[i]); - // 情況三 - else if (dominoes[i] == 'L' && dominoes[j] == 'R') - res += string(mid, '.'); - // 情況四 - else - res += string(mid / 2, 'R') + string(mid % 2, '.') + string(mid / 2, 'L'); - i = j; - cout << res << endl; - } - return res; - } -}; \ No newline at end of file diff --git a/C_plus/83_RemoveDuplicatesFromSortedList.cpp b/C_plus/83_RemoveDuplicatesFromSortedList.cpp deleted file mode 100644 index e1e5101..0000000 --- a/C_plus/83_RemoveDuplicatesFromSortedList.cpp +++ /dev/null @@ -1,76 +0,0 @@ -/** - * Definition for singly-linked list. - * struct ListNode { - * int val; - * ListNode *next; - * ListNode() : val(0), next(nullptr) {} - * ListNode(int x) : val(x), next(nullptr) {} - * ListNode(int x, ListNode *next) : val(x), next(next) {} - * }; - */ -class Solution -{ -public: - ListNode *deleteDuplicates(ListNode *head) - { - // option 1 O(N) time , O(1) space 直接修改節點的值 without extra space - - if (!head) - return head; - - ListNode *slow, *fast; - slow = fast = head; - while (fast) - { - - if (fast->val != slow->val) - { - - // nums[slow] = nums[fast] - slow->next = fast; - // slow++; - slow = slow->next; - } - fast = fast->next; - } - // 斷開後面重複元素的連接 - slow->next = nullptr; - return head; - - // option 1.1 只用單指標處理 - // if(!head) return head; - // ListNode *p = head; - // while(p->next){ - // if(p->next->val==p->val) p->next = p->next->next; - // else p=p->next; - // } - // return head; - - // option 2 O(n^2) time O(1) space brute force - // ListNode *p = head; - - // while(p){ - // ListNode *run = p; - // while(run->next){ - // if(run->next->val==p->val) run->next = run->next->next; - // else run =run->next; - // } - // p=p->next; - // } - - // return head; - - // option 3 O(N) time O(s) space 不能修改節點,用set儲存出現過的值 - // set 容器裡面是會幫你排序的,因為set 是紅黑樹實作的,二元搜尋樹 - // set s; - // for(ListNode *p=head;p;p=p->next){ - // s.insert(p->val); - // } - // ListNode *ret = new ListNode(-1), *p=ret; - // for(auto iter = s.begin();iter!=s.end();++iter){ - // p->next = new ListNode(*iter); - // p = p->next; - // } - // return ret->next; - } -}; \ No newline at end of file diff --git a/C_plus/84*_LargestRectangleinHistogram.cpp b/C_plus/84*_LargestRectangleinHistogram.cpp deleted file mode 100644 index b668824..0000000 --- a/C_plus/84*_LargestRectangleinHistogram.cpp +++ /dev/null @@ -1,35 +0,0 @@ -class Solution -{ -public: - int largestRectangleArea(vector &heights) - { - stack sta; - int ret = 0; - heights.push_back(0); - for (int i = 0; i < heights.size(); ++i) - { - - if (sta.empty() || heights[sta.top()] < heights[i]) - sta.push(i); - else - { - cout << "i: " << i << endl; - while (!sta.empty() && heights[i] <= heights[sta.top()]) - { - int t = sta.top(); - sta.pop(); - if (sta.empty()) - ret = max(ret, heights[t] * (i)); - else - ret = max(heights[t] * (i - sta.top() - 1), ret); - - cout << ret << endl; - - // ret = max(ret , heights[t] * (sta.empty() ?i:(i-sta.top()-1))); - } - sta.push(i); - } - } - return ret; - } -}; \ No newline at end of file diff --git a/C_plus/844_BackspaceStringCompare.cpp b/C_plus/844_BackspaceStringCompare.cpp deleted file mode 100644 index 8cdb57c..0000000 --- a/C_plus/844_BackspaceStringCompare.cpp +++ /dev/null @@ -1,61 +0,0 @@ -class Solution -{ -public: - bool backspaceCompare(string s, string t) - { - - // option 1 O(n) time, O(n) space - // stack sta, sta2; - - // for(char c:s){ - // if(c=='#' && !sta.empty()){ - // sta.pop(); - // } - // else if(c!='#') sta.push(c); - // } - - // for(char c:t){ - // if(c=='#' && !sta2.empty()){ - // sta2.pop(); - // } - // else if(c!='#') sta2.push(c); - // } - - // // check two stack is th same - - // if(sta.size()!=sta2.size()) return false; - // while(!sta.empty() && !sta2.empty()){ - // if(sta.top()!= sta2.top()) return false; - // sta.pop(); - // sta2.pop(); - // } - // return (sta.empty()&&sta2.empty())?true:false; - - // option 2 - // O(n) time and O(1) space - - return text(s) == text(t); - - // option 3 - // O(n) time and O(1) space - string S = "", T = ""; - for (char c : s) - c == '#' ? S.size() > 0 ? S.pop_back() : void() : S.push_back(c); - for (char c : t) - c == '#' ? T.size() > 0 ? T.pop_back() : void() : T.push_back(c); - return S == T; - } - string text(string s) - { - string ret = ""; - for (char c : s) - { - if (c == '#' && !ret.empty()) - ret.pop_back(); - else if (c != '#') - ret.push_back(c); - } - - return ret; - } -}; \ No newline at end of file diff --git a/C_plus/848_ShiftingLetters.cpp b/C_plus/848_ShiftingLetters.cpp deleted file mode 100644 index dc7d544..0000000 --- a/C_plus/848_ShiftingLetters.cpp +++ /dev/null @@ -1,30 +0,0 @@ -class Solution -{ -public: - char shift(char c, int n) - { - int a = (c - 'a' + n) % 26; - return char(a + 'a'); - } - string shiftingLetters(string s, vector &shifts) - { - //prefix sum - if (shifts.empty()) - return ""; - int n = shifts.size(); - // 3 5 9 - // 17 14 9 - - for (int i = n - 2; i > -1; i--) - { - shifts[i] = (shifts[i + 1] + shifts[i]) % 26; - } - - string ret; - for (int i = 0; i < n; ++i) - { - ret += shift(s[i], shifts[i]); - } - return ret; - } -}; \ No newline at end of file diff --git a/C_plus/852_PeakIndexInaMountainArray.cpp b/C_plus/852_PeakIndexInaMountainArray.cpp deleted file mode 100644 index 1a36ace..0000000 --- a/C_plus/852_PeakIndexInaMountainArray.cpp +++ /dev/null @@ -1,63 +0,0 @@ -class Solution -{ -public: - int peakIndexInMountainArray(vector &arr) - { - - // option 1 brute O(n) - // int n=arr.size()-1; - - // for(int i=0;iarr[i+1]) return i; - // if(i==n-1 && arr[i]> arr[i-1]) return i; - // } - // else{ - // if( arr[i]>arr[i-1] && arr[i]>arr[i+1]) return i; - // } - // } - // return 0; - - // option 2 O(n) two pointer - // int l=0,r=arr.size()-1; - // while(l0 && arr[r-1]>arr[r]) r--; - // return r; - - // option 3 binary search O(nlogn) - // int peak = BinarySearch(arr, arr.size()); - // return peak; - - //option 4 根據題意一定存在一個山峰 - for (int i = 1; i < arr.size() - 1; ++i) - { - if (arr[i] > arr[i + 1]) - return i; - } - return 0; - } - int BinarySearch(vector &arr, int n) - { - int l = 0, r = n - 1; - while (l <= r) - { - int mid = l + (r - l) / 2; - cout << mid << endl; - if (mid - 1 >= 0 && mid + 1 <= n - 1) - { - if (arr[mid] > arr[mid - 1] && arr[mid] > arr[mid + 1]) - { - return mid; - } - else if (arr[mid - 1] > arr[mid] && arr[mid] > arr[mid + 1]) - r = mid; - // 防止l=0,r=1 (0+1)/2 = 0,l=0,r=2 (0+2)/2=1; - else - l = mid + 1; - } - else - break; - } - return -1; - } -}; \ No newline at end of file diff --git a/C_plus/855*_ExamRoom.java b/C_plus/855*_ExamRoom.java deleted file mode 100644 index f1847bf..0000000 --- a/C_plus/855*_ExamRoom.java +++ /dev/null @@ -1,99 +0,0 @@ -class ExamRoom { - // 将端点 p 映射到以 p 为左端点的线段 - private Map startMap; - // 将端点 p 映射到以 p 为右端点的线段 - private Map endMap; - // 根据线段长度从小到大存放所有线段 - private TreeSet pq; - private int N; - - public ExamRoom(int N) { - this.N = N; - startMap = new HashMap<>(); - endMap = new HashMap<>(); - // pq = new TreeSet<>((a, b) -> { - // // 算出两个线段的长度 - // int distA = distance(a); - // int distB = distance(b); - // // 长度更长的更大,排后面 - // return distA - distB; - // }); - - pq = new TreeSet<>((a, b) -> { - int distA = distance(a); - int distB = distance(b); - // 如果长度相同,就比较索引 - if (distA == distB) - return b[0] - a[0]; - return distA - distB; - }); - // 在有序集合中先放一个虚拟线段 - addInterval(new int[] {-1, N}); - } - - /* 去除一个线段 */ - private void removeInterval(int[] intv) { - pq.remove(intv); - startMap.remove(intv[0]); - endMap.remove(intv[1]); - } - - /* 增加一个线段 */ - private void addInterval(int[] intv) { - pq.add(intv); - startMap.put(intv[0], intv); - endMap.put(intv[1], intv); - } - - /* 计算一个线段的长度 */ - private int distance(int[] intv) { - // return intv[1] - intv[0] - 1; - int x = intv[0]; - int y = intv[1]; - if (x == -1) return y; - if (y == N) return N - 1 - x; - // 中点和端点之间的长度 - return (y - x) / 2; - } - - public int seat() { - // 从有序集合拿出最长的线段 - int[] longest = pq.last(); - int x = longest[0]; - int y = longest[1]; - int seat; - if (x == -1) { // 情况一 - seat = 0; - } else if (y == N) { // 情况二 - seat = N - 1; - } else { // 情况三 - seat = (y - x) / 2 + x; - } - // 将最长的线段分成两段 - int[] left = new int[] {x, seat}; - int[] right = new int[] {seat, y}; - removeInterval(longest); - addInterval(left); - addInterval(right); - return seat; - - } - - public void leave(int p) { - // 将 p 左右的线段找出来 - int[] right = startMap.get(p); - int[] left = endMap.get(p); - // 合并两个线段成为一个线段 - int[] merged = new int[] {left[0], right[1]}; - removeInterval(left); - removeInterval(right); - addInterval(merged); - } -} - -/** - * Your ExamRoom object will be instantiated and called as such: - * ExamRoom obj = new ExamRoom(n); - * int param_1 = obj.seat(); - * obj.leave(p); - */ \ No newline at end of file diff --git a/C_plus/86_Partition_List.cpp b/C_plus/86_Partition_List.cpp deleted file mode 100644 index 4f0c1b4..0000000 --- a/C_plus/86_Partition_List.cpp +++ /dev/null @@ -1,69 +0,0 @@ -/** - * Definition for singly-linked list. - * struct ListNode { - * int val; - * ListNode *next; - * ListNode() : val(0), next(nullptr) {} - * ListNode(int x) : val(x), next(nullptr) {} - * ListNode(int x, ListNode *next) : val(x), next(next) {} - * }; - */ -class Solution -{ -public: - ListNode *partition(ListNode *head, int x) - { - // option 1 O(N) time and O(N) space - // 1. 分別照順序收集小於x,大於等於x的 - // 2. 將兩個queue串起來 - // if(!head) return head; - // queue q, q2; - // ListNode *p= head; - // ListNode *ret = new ListNode(-201); - // while(p){ - // if(p->valval); - // else q2.push(p->val); - // p=p->next; - // } - - // p=ret; - // while(!q.empty()){ - // int k = q.front(); - // ListNode *t = new ListNode(k); - // q.pop(); - // if(t) p->next = t; - // p=p->next; - // } - // while(!q2.empty()){ - - // int k = q2.front(); - // cout<next = new ListNode(k); - // p=p->next; - // } - // return ret->next; - - // option 2 O(N) time and O(1) space two pointer - // 1. 分別new 兩個起始節點,稍後travese linked list 判斷該節點大於等於還是小於,已分別放入不同串列 - // 2. 將兩個串列串起來 - ListNode *p1 = new ListNode(0), *ret = p1; - ListNode *p2 = new ListNode(0), *t = p2; - ListNode *p = head; - for (; p; p = p->next) - { - if (p->val < x) - { - p1->next = new ListNode(p->val); - p1 = p1->next; - } - else - { - p2->next = new ListNode(p->val); - p2 = p2->next; - } - } - p1->next = t->next; - return ret->next; - } -}; \ No newline at end of file diff --git a/C_plus/870*_AdvantageShuffle.cpp b/C_plus/870*_AdvantageShuffle.cpp deleted file mode 100644 index 487531d..0000000 --- a/C_plus/870*_AdvantageShuffle.cpp +++ /dev/null @@ -1,42 +0,0 @@ - -class Solution -{ -public: - vector advantageCount(vector &nums1, vector &nums2) - { - // option 1 - int n = nums1.size(); - - priority_queue > pq; - for (int i = 0; i < nums2.size(); ++i) - { - pq.push(make_pair(nums2[i], i)); - } - // (0,1) (1,10) (2,4) (3,11) => (3,11) (1,10) (2,4) (0,1) - // 2 7 11 15 => 15 11 7 2 - - sort(nums1.begin(), nums1.end()); - - int left = 0, right = n - 1; - vector ret(n, 0); - - while (!pq.empty()) - { - auto pair = pq.top(); - pq.pop(); - int i = pair.second, maxVal = pair.first; - if (maxVal < nums1[right]) - { - ret[i] = nums1[right]; - right--; - } - else - { - // 比不過,拿最小值,送人頭 - ret[i] = nums1[left]; - left++; - } - } - return ret; - } -}; \ No newline at end of file diff --git a/C_plus/872_Leaf-SimilarTrees.cpp b/C_plus/872_Leaf-SimilarTrees.cpp deleted file mode 100644 index 0153f5e..0000000 --- a/C_plus/872_Leaf-SimilarTrees.cpp +++ /dev/null @@ -1,62 +0,0 @@ -/* - * @Author: yuan - * @Date: 2021-07-17 09:21:24 - * @LastEditTime: 2021-07-17 09:21:24 - * @FilePath: /leet_code/C_plus/872_Leaf-SimilarTrees.cpp - */ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution -{ -public: - void getLeaves(TreeNode *root, vector &leaves) - { - // preorder traverse - if (!root) - return; - if (root->left == nullptr && root->right == nullptr) - leaves.push_back(root->val); - - getLeaves(root->left, leaves); - getLeaves(root->right, leaves); - } - bool leafSimilar(TreeNode *root1, TreeNode *root2) - { - // option 1 vector - // vector leaves1; - // vector leaves2; - // getLeaves(root1, leaves1); - // getLeaves(root2, leaves2); - - // return leaves1 == leaves2; - - // option 1.1 instead of vector, string - string leaves1 = ""; - string leaves2 = ""; - getLeaves(root1, leaves1); - getLeaves(root2, leaves2); - - return leaves1 == leaves2; - } - - void getLeaves(TreeNode *root, string &leaves) - { - // preorder traverse - if (!root) - return; - if (root->left == nullptr && root->right == nullptr) - leaves.append(to_string(root->val) + "-"); - - getLeaves(root->left, leaves); - getLeaves(root->right, leaves); - } -}; \ No newline at end of file diff --git a/C_plus/875*_KokoEatingBananas.cpp b/C_plus/875*_KokoEatingBananas.cpp deleted file mode 100644 index 20d92e3..0000000 --- a/C_plus/875*_KokoEatingBananas.cpp +++ /dev/null @@ -1,83 +0,0 @@ -class Solution -{ -public: - int f(vector &piles, int x) - { - // 定義:吃香蕉速度 x根 每小時,則需要 f(x) 小時吃完所有香蕉 - // f 隨著x增加 單調遞減, f(15) = 4, f(8) = 5, f(15) = 2 - // piles = 3 6 7 11 , x = 15 - // hours = 1 2 3 4 - - // piles = 3 6 7 11 , x = 8 - // hours = 1 2 3 5 - - // piles = 3 6 7 11 , x = 2 - // hours = 2 5 9 15 - - int hours = 0; - for (int i = 0; i < piles.size(); ++i) - { - hours += piles[i] / x; - if (piles[i] % x > 0) - hours++; // 不足一樣算一小時,意味著假設每小時只能吃2根,但此堆只剩ㄧ根,一樣要花一小時,且不能吃其它堆 - } - return hours; - } - int minEatingSpeed(vector &piles, int h) - { - // 不像先前的二元搜尋法直接在x的值域[3,6,7,11]搜尋,在y的值域搜尋> - // 所以left, right變數不再是維護索引,而是索引之值。 - // 1 <= piles[i] <= 1e+9 - // tips 合併冗余if 可增加效率 - int left = 1; - int right = 1e+9 + 1; // 因為搜尋空間是左閉右開,所以+1 - - // option 1 窮舉法 - // for(int i = left;i h) - { - // 怎們讓f(x) 變小,x變大 - left = mid + 1; - } - else if (f(piles, mid) < h) - { - // 怎們讓f(x) 變大,x變小 - right = mid; - } - } - return left; - - // option 2.1 improved - - // while(left < right){ - // int mid = left + (right - left)/2; - // int target = f(piles ,mid); - // cout<next; - // } - // p=head; - // size /=2; - // while(size){ - // size--; - // p=p->next; - // } - // return p; - - // option 2 O(n) slow fast point - ListNode *slow =head, *fast=head; - while(fast && fast->next){ - slow = slow->next; - fast= fast->next->next; - } - return slow; - - // option 3 use STL - vector ret(100); - int cur = 0; - while (head) - { - ret[cur++] = head; - head = head->next; - } - return ret[cur / 2]; - } -}; \ No newline at end of file diff --git a/C_plus/877*_StoneGame.cpp b/C_plus/877*_StoneGame.cpp deleted file mode 100644 index 4cb1fbc..0000000 --- a/C_plus/877*_StoneGame.cpp +++ /dev/null @@ -1,60 +0,0 @@ -class Solution -{ -public: - bool stoneGame(vector &piles) - { - // option 1 math - // 假設雙方都很聰明 - // 條件: 1. 總共有奇數個石頭 2. 堆數是偶數 - // 因為總共有奇數個石頭,所以一定會有勝負。 - // 先下手可以控制自己拿到的是偶數堆還是奇數堆, - // 2 1 9 5 奇數堆 1、3和偶數堆2、4 - // 以上面的例子,最開始可以選擇第1堆或第四堆,如果想要偶數堆就拿第四堆,這樣對手不管怎麼拿都是奇數堆 - - // return true; - - // option 2 dp - int n = piles.size(); - // 初始化 dp - // dp 狀態 : 開始的索引 i 結束的索引j 當前輪到的人 - vector > > dp(n, vector >(n, tuple(0, 0))); - // 举例理解一下,假设 piles = [3, 9, 1, 2],索引从 0 开始 - // dp[0][1].fir = 9 意味着:面对石头堆 [3, 9],先手最终能够获得 9 分。 - // dp[1][3].sec = 2 意味着:面对石头堆 [9, 1, 2],后手最终能够获得 2 分。 - - // base case - for (int i = 0; i < n; ++i) - { - get<0>(dp[i][i]) = piles[i]; - // dp[i][i].first = piles[i]; - get<1>(dp[i][i]) = 0; - // dp[i][i].second = 0 ; - } - - // 斜著遍歷數組 - for (int l = 2; l <= n; ++l) - { - for (int i = 0; i <= n - l; ++i) - { - int j = l + i - 1; - // 先手選擇最走邊或是最右邊的分數 - int left = piles[i] + get<1>(dp[i + 1][j]); - int right = piles[j] + get<1>(dp[i][j - 1]); - - if (left > right) - { - get<0>(dp[i][j]) = left; - get<1>(dp[i][j]) = get<0>(dp[i + 1][j]); - } - else - { - get<0>(dp[i][j]) = right; - get<1>(dp[i][j]) = get<0>(dp[i][j - 1]); - } - } - } - tuple ret = dp[0][n - 1]; - // cout<(ret)<<" "<(ret)<(ret) - get<1>(ret); - } -}; \ No newline at end of file diff --git a/C_plus/887*_SuperEggDrop.cpp b/C_plus/887*_SuperEggDrop.cpp deleted file mode 100644 index b41d915..0000000 --- a/C_plus/887*_SuperEggDrop.cpp +++ /dev/null @@ -1,95 +0,0 @@ -class Solution -{ -private: - // unordered_map, int> memo; - map, int> memo; - -public: - int dp(int k, int n) - { - - // 狀態、選擇 - // 當前狀態為 (K個雞蛋、N樓層),返回這個狀態的最佳解 - - //base case - // 如果雞蛋數只有一顆,那只能限性掃描才不會打破超過一顆 - if (k == 1) - return n; - // 樓層為0,顯然不需要扔雞蛋 - if (n == 0) - return 0; - - // 避免重複計算 - if (memo.count(make_pair(k, n))) - return memo[make_pair(k, n)]; - - int ret = INT_MAX; - - // option 1 memo pattern time out - // O(K*N^2) time, O(KN) space - // 窮舉所有可能 - // for(int i=1;i<=n ;++i){ - - // ret = min(ret, 1 + max( - // dp(k, n-i), - // dp(k-1,i-1) - // ) - // ); - // } - - // option 2 用binary search代替 dp的線性搜尋 - // O(K*N* logN) time, O(KN) space - int lo = 1, hi = n; - while (lo <= hi) - { - int mid = lo + (hi - lo) / 2; - int broken = dp(k - 1, mid - 1); // 碎 - int not_broken = dp(k, n - mid); // 沒碎 - // ret = min( max(碎, 沒碎) + 1) - - if (broken > not_broken) - { - hi = mid - 1; - ret = min(ret, broken + 1); - } - else - { - lo = mid + 1; - ret = min(ret, not_broken + 1); - } - } - - memo[make_pair(k, n)] = ret; - return ret; - } - int superEggDrop(int k, int n) - { - - // option 1 memo pattern time out = up-bottom - - // return dp(k, n); - - // option 2 用binary search代替 dp的線性搜尋 - // return dp(k, n); - - // option 3 math - - // m 最多不會超過N次 (線性掃描) - vector > dp(k + 1, vector(n + 1, 0)); - - // base case - // dp[0][...] = 0 - // dp[...][0] = 0 - // - int m = 0; - while (dp[k][m] < n) - { - m++; - for (int j = 1; j <= k; j++) - { - dp[j][m] = dp[j][m - 1] + dp[j - 1][m - 1] + 1; - } - } - return m; - } -}; \ No newline at end of file diff --git a/C_plus/889*_ConstructBinaryTreefromPreorderandPostorderTraversal.cpp b/C_plus/889*_ConstructBinaryTreefromPreorderandPostorderTraversal.cpp deleted file mode 100644 index 4205ec0..0000000 --- a/C_plus/889*_ConstructBinaryTreefromPreorderandPostorderTraversal.cpp +++ /dev/null @@ -1,38 +0,0 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution -{ -public: - TreeNode *constructFromPrePost(vector &preorder, int lo, int hi, vector &postorder, int l, int r) - { - - if (lo > hi || l > r) - return nullptr; - - TreeNode *root = new TreeNode(preorder[lo]); - if (lo == hi) - return root; - - int idx = l; - while (postorder[idx] != preorder[lo + 1]) - idx++; - int len = idx - l + 1; - - root->left = constructFromPrePost(preorder, lo + 1, lo + len, postorder, l, idx); - root->right = constructFromPrePost(preorder, lo + len + 1, hi, postorder, idx + 1, r - 1); - return root; - } - TreeNode *constructFromPrePost(vector &preorder, vector &postorder) - { - return constructFromPrePost(preorder, 0, preorder.size() - 1, postorder, 0, postorder.size() - 1); - } -}; \ No newline at end of file diff --git a/C_plus/88_MergeSortedArray.cpp b/C_plus/88_MergeSortedArray.cpp deleted file mode 100644 index 677ba77..0000000 --- a/C_plus/88_MergeSortedArray.cpp +++ /dev/null @@ -1,47 +0,0 @@ -class Solution -{ -public: - void merge(vector &nums1, int m, vector &nums2, int n) - { - - // option 1 先串起來在用插入排序 O(n^2) time - - // for(int i=m, j=0;i-1 && key nums(m + n, 0); - - int i = 0, j = 0, k = 0; - while (i < m && j < n) - { - if (nums1[i] <= nums2[j]) - { - nums[k++] = nums1[i]; - i++; - } - else if (nums1[i] > nums2[j]) - { - nums[k++] = nums2[j]; - j++; - } - } - - while (i < m) - nums[k++] = nums1[i++]; - while (j < n) - nums[k++] = nums2[j++]; - nums1 = nums; - } -}; \ No newline at end of file diff --git a/C_plus/89*_GrayCode.cpp b/C_plus/89*_GrayCode.cpp deleted file mode 100644 index 644e2f4..0000000 --- a/C_plus/89*_GrayCode.cpp +++ /dev/null @@ -1,53 +0,0 @@ -class Solution -{ -public: - vector grayCode(int n) - { - // 參考https://leetcode.com/discuss/explore/july-leetcoding-challenge-2021/1308587/Gray-Code-or-Recursion-%2B-Iterative-wExplanation - - // option 1 - // if n= 1 , {0,1} - // if n=2 , {00,01,11,10} - // if n= 3, {000,001,011,010,110,111,101,100} - // 以n=3當例子,前半段{000,001,011,010} 可以當作是n=2 {00,01,11,10} 在前面加上0, - // 後半段{110,111,101,100} ,沒那麼直觀,是 reverse {00,01,11,10}(={10,11,01,00}) 再前面加上1 - - // vector gray = {"0","1"}; - - // if(n==1) return {0,1}; - - // for(int i=2;i<=n;i++){ - // int size = gray.size(); - // vector second = gray; - // for(auto &r :gray){ - // r = "0"+r; - // } - - // reverse(second.begin(), second.end()); - // for(auto &s:second){ - // s = "1" +s; - // } - // gray.insert(gray.end(), second.begin(), second.end()); - // } - - // // consert string to int - // vector ret; - // for(string g:gray) ret.push_back(stoi(g,0,2)); // better than stoi(g); - // return ret; - - // option 2 bit manipulation - // n = 2 {00,01,11,10} 長度 4 = 1<<2 - // n = 3 {000,001,011,010,110,111,101,100} 長度 8 1<<3 - // n = 2 為例, - // 00^(00) = 00 , i=0 - // 01^(00) = 01 , i=1 - // 10^(01) = 11, i=2 - // 11^(01) = 10, i=3 - vector ans; - for (int i = 0; i < (1 << n); i++) - { - ans.push_back(i ^ (i >> 1)); - } - return ans; - } -}; \ No newline at end of file diff --git a/C_plus/895*_MaximumFrequencyStack.cpp b/C_plus/895*_MaximumFrequencyStack.cpp deleted file mode 100644 index 033b24e..0000000 --- a/C_plus/895*_MaximumFrequencyStack.cpp +++ /dev/null @@ -1,41 +0,0 @@ -class FreqStack -{ -private: - int maxFreq; - unordered_map valToFreq; - unordered_map > freqToVals; - -public: - FreqStack() - { - maxFreq = 0; - } - - void push(int val) - { - int freq = valToFreq[val]++; - maxFreq = max(maxFreq, freq); - - freqToVals[freq].push(val); - } - - int pop() - { - stack &vals = freqToVals[maxFreq]; - int v = vals.top(); - vals.pop(); - valToFreq[v]--; - if (vals.empty()) - { - maxFreq--; - } - return v; - } -}; - -/** - * Your FreqStack object will be instantiated and called as such: - * FreqStack* obj = new FreqStack(); - * obj->push(val); - * int param_2 = obj->pop(); - */ \ No newline at end of file diff --git a/C_plus/897*_IncreasingOrderSearchTree.cpp b/C_plus/897*_IncreasingOrderSearchTree.cpp deleted file mode 100644 index 7be26ca..0000000 --- a/C_plus/897*_IncreasingOrderSearchTree.cpp +++ /dev/null @@ -1,60 +0,0 @@ -/* - * @Author: yuan - * @Date: 2021-07-17 09:49:09 - * @LastEditTime: 2021-07-17 09:49:09 - * @FilePath: /leet_code/C_plus/897*_IncreasingOrderSearchTree.cpp - */ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution -{ -public: - void inorder(TreeNode *root, vector &vec) - { - if (!root) - return; - - inorder(root->left, vec); - vec.push_back(root->val); - inorder(root->right, vec); - } - TreeNode *increasingBST(TreeNode *root) - { - // option 1 直覺用vector紀錄所有點排序後 - // vector vec; - // inorder(root, vec); - - // TreeNode *cur = new TreeNode(vec[0]), *ret = cur; - // for(int i=1;iright = new TreeNode(vec[i]); - // cur = cur->right; - // } - // return ret; - - // option 2 - TreeNode *ans; - TreeNode *temp = new TreeNode(); - ans = temp; - inorder(temp, root); - return ans->right; - } - void inorder(TreeNode *&ans, TreeNode *root) - { - if (!root) - return; - inorder(ans, root->left); - ans->left = nullptr; - ans->right = new TreeNode(root->val); - ans = ans->right; - inorder(ans, root->right); - } -}; \ No newline at end of file diff --git a/C_plus/8_StringToInteger.cpp b/C_plus/8_StringToInteger.cpp deleted file mode 100644 index f1640b3..0000000 --- a/C_plus/8_StringToInteger.cpp +++ /dev/null @@ -1,25 +0,0 @@ -class Solution -{ -public: - int myAtoi(string s) - { - int l = 0; - int ret = 0; - while (s[l] == ' ') - l++; - int flag = 1; - if (s[l] == '-' || s[l] == '+') - { - flag = (s[l++] == '+') ? 1 : -1; - } - while (s[l] >= '0' && s[l] <= '9') - { - if (ret > INT_MAX / 10 || (ret == INT_MAX / 10 && s[l] - '0' > INT_MAX % 10)) - { - return flag == 1 ? INT_MAX : INT_MIN; - } - ret = 10 * ret + (s[l++] - '0'); - } - return flag * ret; - } -}; \ No newline at end of file diff --git a/C_plus/90*_SubsetsII.cpp b/C_plus/90*_SubsetsII.cpp deleted file mode 100644 index 9e56972..0000000 --- a/C_plus/90*_SubsetsII.cpp +++ /dev/null @@ -1,28 +0,0 @@ -class Solution -{ -public: - // Input: nums = [1,2,2] - // Output: [[],[1],[1,2],[1,2,2],[2],[2,2]] - void traverse(vector &nums, int start, vector &path, vector > &ret) - { - - ret.push_back(path); - - for (int i = start; i < nums.size(); ++i) - { - if (i > start && nums[i] == nums[i - 1]) - continue; - path.push_back(nums[i]); - traverse(nums, i + 1, path, ret); - path.pop_back(); - } - } - vector > subsetsWithDup(vector &nums) - { - sort(nums.begin(), nums.end()); - vector > ret; - vector path; - traverse(nums, 0, path, ret); - return ret; - } -}; \ No newline at end of file diff --git a/C_plus/901*_OnlineStockSpan.cpp b/C_plus/901*_OnlineStockSpan.cpp deleted file mode 100644 index abe841a..0000000 --- a/C_plus/901*_OnlineStockSpan.cpp +++ /dev/null @@ -1,37 +0,0 @@ -class StockSpanner -{ -public: - // vector ret; // option 1 - stack > s; // option 2 - StockSpanner() - { - } - - int next(int price) - { - // option 1 maintain vector O(n) time - // int res =0; - // ret.push_back(price); - // for(int i=ret.size()-1;i>-1;i--){ - // if(price >= ret[i]) res++; - // else break; - // } - // return res; - - // option 2 maintain stack - int res = 1; - while (!s.empty() && s.top().first <= price) - { - res += s.top().second; - s.pop(); - } - s.push({price, res}); - return res; - } -}; - -/** - * Your StockSpanner object will be instantiated and called as such: - * StockSpanner* obj = new StockSpanner(); - * int param_1 = obj->next(price); - */ \ No newline at end of file diff --git a/C_plus/905_SortArrayByParity.cpp b/C_plus/905_SortArrayByParity.cpp deleted file mode 100644 index 1ce6fc6..0000000 --- a/C_plus/905_SortArrayByParity.cpp +++ /dev/null @@ -1,31 +0,0 @@ -class Solution -{ -public: - vector sortArrayByParity(vector &nums) - { - // option 1 O(n) two pointer - - // int l=0,r=nums.size()-1; - // while(l B B(2 2) or V(22) - // 26 => B B F(2 2 6) V F(22 6) B Z (2 26) - if (s.empty() || s[0] == '0') - return 0; - int n = s.size(); - vector dp(n + 1, 0); - dp[0] = 1; - for (int i = 1; i <= n; ++i) - { - if (s[i - 1] != '0') - dp[i] = dp[i - 1]; - - if (i > 1 && (s[i - 2] == '1' || (s[i - 2] == '2' && s[i - 1] <= '6'))) - { - dp[i] += dp[i - 2]; - } - } - return dp.back(); - } -}; \ No newline at end of file diff --git a/C_plus/915_PartitionArrayintoDisjointIntervals.cpp b/C_plus/915_PartitionArrayintoDisjointIntervals.cpp deleted file mode 100644 index 97c0e7e..0000000 --- a/C_plus/915_PartitionArrayintoDisjointIntervals.cpp +++ /dev/null @@ -1,73 +0,0 @@ -class Solution -{ -public: - int partitionDisjoint(vector &nums) - { - - int n = nums.size(); - - // 5 0 3 8 6 - // 5 5 5 8 8 lmax - // 0 0 3 6 6 rmin - - // 1 1 1 0 6 12 - // 1 1 1 1 6 12 //lmax - // 0 0 0 0 6 12 // rmin - - // vector lmax(n, nums[0]) , rmin(n, nums[n-1]); - - // for(int i=1;i-1;i--) rmin[i] = min(rmin[i+1], nums[i] ); - - // // for(int l:lmax) cout< rmin(n, nums[n-1]); - // for(int i=n-2;i>-1;i--) rmin[i] = min(rmin[i+1], nums[i] );; - - // int lmax = INT_MIN; - // for(int i=0;i &nums) - { - - // 1 -2 3 -2 => total 0 - //max 1 -1 3 -1 - //min 1 -2 1 -2 - // ans = max( 3 , sum - -2) - - // 5 -3 5 => sum = 7 - //max 5 -2 5 - //min 5 -3 -2 - //ans = max( 5 , 7 - -3) - - // 3 -1 2 -1 => sum = 3 - //max 3 2 4 3 - //min 3 -1 1 -1 - // ans = max(4, 3 - -1) - // 如果最大子陣列在陣列中,取最大。如果在陣列頭與尾,代表最小出現在陣列中,取最小在用陣列和減去最小子陣列,即是case2的最大子陣列 - int ans = -30000, n = nums.size(), sum = 0; - int local_max = 0, local_min = 0, global_max = INT_MIN, global_min = INT_MAX; - for (int i = 0; i < n; ++i) - { - sum += nums[i]; - local_max = max(local_max + nums[i], nums[i]); - local_min = min(local_min + nums[i], nums[i]); - global_max = max(local_max, global_max); - global_min = min(local_min, global_min); - } - if (global_min == sum) - return global_max; - return max(global_max, sum - global_min); - } -}; \ No newline at end of file diff --git a/C_plus/921*_MinimumAddtoMakeParenthesesValid.cpp b/C_plus/921*_MinimumAddtoMakeParenthesesValid.cpp deleted file mode 100644 index 44842f8..0000000 --- a/C_plus/921*_MinimumAddtoMakeParenthesesValid.cpp +++ /dev/null @@ -1,34 +0,0 @@ -class Solution -{ -public: - int minAddToMakeValid(string s) - { - // ret 紀錄插入次數 - int ret = 0; - // need 變數 紀錄右括號 的需求量 - int need = 0; - - for (int i = 0; i < s.size(); ++i) - { - if (s[i] == '(') - { - // 對右括號的需求+1 - need++; - } - - if (s[i] == ')') - { - // 對右括號的需求-1 - need--; - if (need == -1) - { - need = 0; - // 需要插入一個左括號 - ret++; - } - } - } - - return ret + need; - } -}; \ No newline at end of file diff --git a/C_plus/922_SortArrayByParityII.cpp b/C_plus/922_SortArrayByParityII.cpp deleted file mode 100644 index 89b97ff..0000000 --- a/C_plus/922_SortArrayByParityII.cpp +++ /dev/null @@ -1,35 +0,0 @@ -class Solution -{ -public: - vector sortArrayByParityII(vector &nums) - { - - // vector ret = nums; - // int n = nums.size(); - // int j=0,k=1; - // for(int i=0;i &arr, int target) - { - // two point O(n^2) time and O(1) space - int cnt = 0; - int mod = 1e+9 + 7; - int n = arr.size(); - sort(arr.begin(), arr.end()); - for (int i = 0; i < n - 2; ++i) - { - int l = i + 1, r = n - 1; - while (l < r) - { - int sum = arr[i] + arr[l] + arr[r]; - if (sum == target) - { - int left = 1, right = 1; - while (l + left <= r && arr[l + left] == arr[l]) - left++; - while (l + left <= r - right && arr[r - right] == arr[r]) - right++; - if (arr[l] == arr[r]) - cnt += (r - l + 1) * (r - l) / 2; - else - cnt += left * right; - cnt = cnt % mod; - l += left; - r -= right; - } - else if (sum < target) - l++; - else - r--; - } - } - - return cnt; - } -}; \ No newline at end of file diff --git a/C_plus/926*_FlipStringtoMonotoneIncreasing.cpp b/C_plus/926*_FlipStringtoMonotoneIncreasing.cpp deleted file mode 100644 index 608cc62..0000000 --- a/C_plus/926*_FlipStringtoMonotoneIncreasing.cpp +++ /dev/null @@ -1,33 +0,0 @@ -class Solution -{ -public: - int minFlipsMonoIncr(string s) - { - - // two dp - // dp0[i] 代表 [0..i-1] 子字串 最少的將 1 轉成 0 的個數,進而形成單調字串 - // dp1[j] 代表 [j..n-1] 子字串 最少的將 0 轉成 1 的個數,進而形成單調字串 - // 最後 dp0[i] + dp1[j] 最小的時候 即為答案 - - // 00011000 - //dp0 000012222 - //dp1 654333210 - - int n = s.size(); - int ret = INT_MAX; - vector dp0(n + 1), dp1(n + 1); - for (int i = 1; i <= n; ++i) - { - dp0[i] += dp0[i - 1] + (s[i - 1] == '1' ? 1 : 0); - } - for (int j = n - 1; j > -1; --j) - { - dp1[j] += dp1[j + 1] + (s[j] == '1' ? 0 : 1); - } - - for (int i = 0; i <= n; ++i) - ret = min(ret, dp0[i] + dp1[i]); - - return ret; - } -}; \ No newline at end of file diff --git a/C_plus/927*_ThreeEqualParts.cpp b/C_plus/927*_ThreeEqualParts.cpp deleted file mode 100644 index f2b657d..0000000 --- a/C_plus/927*_ThreeEqualParts.cpp +++ /dev/null @@ -1,61 +0,0 @@ -class Solution -{ -public: - vector threeEqualParts(vector &arr) - { - int countNumberOfOnes = 0; - for (int a : arr) - countNumberOfOnes += a; - if (countNumberOfOnes == 0) - return {0, (int)arr.size() - 1}; - if (countNumberOfOnes % 3 != 0) - return {-1, -1}; - - int k = countNumberOfOnes / 3; - int i, start, end, mid; - int size = arr.size(); - // 1. find the first 1 in the array , store start variable - for (i = 0; i < size; ++i) - { - if (arr[i] == 1) - break; - } - start = i; - - // 2. find (k+1)th 1 in the array - int count1 = 0; - for (i = 0; i < size; ++i) - { - if (arr[i] == 1) - { - count1++; - } - if (count1 == k + 1) - break; - } - mid = i; - // 3. find (2*k+1)th 1 in the array - count1 = 0; - for (i = 0; i < size; ++i) - { - if (arr[i] == 1) - { - count1++; - } - if (count1 == 2 * k + 1) - break; - } - end = i; - - // 4. Match all values till the end of the array - while (end < size && arr[start] == arr[mid] && arr[mid] == arr[end]) - { - start++; - mid++; - end++; - } - if (end == size) - return {start - 1, mid}; - return {-1, -1}; - } -}; \ No newline at end of file diff --git a/C_plus/929_UniqueEmailAddresses.cpp b/C_plus/929_UniqueEmailAddresses.cpp deleted file mode 100644 index 6eddc14..0000000 --- a/C_plus/929_UniqueEmailAddresses.cpp +++ /dev/null @@ -1,44 +0,0 @@ -class Solution -{ -public: - int numUniqueEmails(vector &emails) - { - unordered_set dict; - for (string email : emails) - { - - int n = email.size(); - int sp = 0; - while (sp < n && email[sp] != '@') - sp++; - if (email[sp] != '@') - { - break; - } - // convert - string temp = ""; - - for (int i = 0; i < sp; ++i) - { - if (email[i] == '+') - break; - else if (email[i] == '.') - continue; - else - { - temp += email[i]; - } - } - temp += '@'; - for (int i = sp + 1; i < n; ++i) - { - temp += email[i]; - } - if (!temp.empty()) - { - dict.insert(temp); - } - } - return dict.size(); - } -}; \ No newline at end of file diff --git a/C_plus/92_ReverseLinkedListII.cpp b/C_plus/92_ReverseLinkedListII.cpp deleted file mode 100644 index ca7d2e9..0000000 --- a/C_plus/92_ReverseLinkedListII.cpp +++ /dev/null @@ -1,64 +0,0 @@ -/** - * Definition for singly-linked list. - * struct ListNode { - * int val; - * ListNode *next; - * ListNode() : val(0), next(nullptr) {} - * ListNode(int x) : val(x), next(nullptr) {} - * ListNode(int x, ListNode *next) : val(x), next(next) {} - * }; - */ -class Solution -{ -private: - ListNode *successor = nullptr; - -public: - ListNode *reverseN(ListNode *head, int n) - { - if (n == 1) - { - successor = head->next; - return head; - } - ListNode *node = reverseN(head->next, n - 1); - head->next->next = head; - head->next = successor; - return node; - - // option 2 - if (!head || !head->next) - return head; - ListNode *pre = new ListNode(-1), *cur = head; - pre->next = head; - // while(cur->next){ - for (int i = 0; i < r-1; ++i) - { - ListNode *temp = cur->next; - cur->next = temp->next; - temp->next = pre->next; - pre->next = temp; - } - return pre->next; - } - ListNode *reverseBetween(ListNode *head, int left, int right) - { - // if(!head) return head; - // ListNode *pre = new ListNode(-1), *ret = pre; - // pre->next = head; - // for(int i=0;inext; - // ListNode *cur = pre->next; - // for(int i=left;inext; - // cur->next = temp->next; - // temp->next = pre->next; - // pre->next = temp; - // } - // return ret->next; - if (left == 1) - return reverseN(head, right); - - head->next = reverseBetween(head->next, left - 1, right - 1); - return head; - } -}; \ No newline at end of file diff --git a/C_plus/931*_MinimumFallingPathSum.cpp b/C_plus/931*_MinimumFallingPathSum.cpp deleted file mode 100644 index ab2449a..0000000 --- a/C_plus/931*_MinimumFallingPathSum.cpp +++ /dev/null @@ -1,94 +0,0 @@ -class Solution -{ -public: - int dp(vector > &matrix, int i, int j) - { - - // 非法索引 - if (i < 0 || j < 0 || i > matrix.size() || j >= matrix[0].size()) - { - return 99999; - } - - //base case - if (i == 0) - return matrix[i][j]; - - // - return matrix[i][j] + min( - dp(matrix, i - 1, j), - min( - dp(matrix, i - 1, j - 1), - dp(matrix, i - 1, j + 1))); - } - - int dp(vector > &matrix, int i, int j, vector > &memo) - { - // 非法索引 - if (i < 0 || j < 0 || i > matrix.size() || j >= matrix[0].size()) - { - return 99999; - } - - //base case - if (i == 0) - return matrix[i][j]; - - // 備忘錄有了,防止重複計算 - if (memo[i][j] != 101) - return memo[i][j]; - - memo[i][j] = matrix[i][j] + min( - dp(matrix, i - 1, j, memo), - min( - dp(matrix, i - 1, j - 1, memo), - dp(matrix, i - 1, j + 1, memo))); - - return memo[i][j]; - } - int minFallingPathSum(vector > &matrix) - { - // option 1 brute force time out 不愧是medium題目 - // int n = matrix.size(); - // int ret = INT_MAX; - // for(int i= 0;i>memo(n, vector(m,101)); - // // 初始化備忘錄 - - // for(int i= 0;i > dp = matrix; - int ret = INT_MAX; - for (int i = 1; i < n; ++i) - { - for (int j = 0; j < m; ++j) - { - if (j == 0) - dp[i][j] += min(dp[i - 1][j], dp[i - 1][j + 1]); - else if (j == m - 1) - dp[i][j] += min(dp[i - 1][j - 1], dp[i - 1][j]); - else - dp[i][j] += min(dp[i - 1][j], min(dp[i - 1][j - 1], dp[i - 1][j + 1])); - - if (i == n - 1) - ret = min(ret, dp[i][j]); - } - } - - return ret; - } -}; \ No newline at end of file diff --git a/C_plus/938*_RangeSumofBST.cpp b/C_plus/938*_RangeSumofBST.cpp deleted file mode 100644 index 8d42da6..0000000 --- a/C_plus/938*_RangeSumofBST.cpp +++ /dev/null @@ -1,48 +0,0 @@ -/* - * @Author: yuan - * @Date: 2021-07-17 09:59:47 - * @LastEditTime: 2021-07-17 09:59:47 - * @FilePath: /leet_code/C_plus/938*_RangeSumofBST.cpp - */ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution -{ -public: - void inorder(TreeNode *root, int &ans, int &low, int &high) - { - if (!root) - return; - - inorder(root->left, ans, low, high); - if (root->val >= low && root->val <= high) - ans += root->val; - - inorder(root->right, ans, low, high); - } - int rangeSumBST(TreeNode *root, int low, int high) - { - // option 1 easy to understand - // int ans = 0 ; - // inorder(root, ans, low, high); - // return ans; - - // option 2 make use of property of BST - if (!root) - return 0; - if (root->val < low) - return rangeSumBST(root->right, low, high); - else if (root->val > high) - return rangeSumBST(root->left, low, high); - return rangeSumBST(root->left, low, high) + rangeSumBST(root->right, low, high) + root->val; - } -}; \ No newline at end of file diff --git a/C_plus/93_RestoreIPAddresses.cpp b/C_plus/93_RestoreIPAddresses.cpp deleted file mode 100644 index f2ad453..0000000 --- a/C_plus/93_RestoreIPAddresses.cpp +++ /dev/null @@ -1,39 +0,0 @@ -class Solution -{ -public: - void helper(string s, int k, string out, vector &ret) - { - if (k == 0) - { - if (s.empty()) - ret.push_back(out); - } - else - { - for (int i = 1; i <= 3; ++i) - { - if (s.size() >= i && isValid(s.substr(0, i))) - { - if (k == 1) - helper(s.substr(i), k - 1, out + s.substr(0, i), ret); - else - helper(s.substr(i), k - 1, out + s.substr(0, i) + ".", ret); - } - } - } - } - bool isValid(string s) - { - if (s.empty() || s.size() > 3 || (s.size() > 1 && s[0] == '0')) - return false; - int ret = atoi(s.c_str()); - return ret <= 255 && ret >= 0; - } - vector restoreIpAddresses(string s) - { - - vector ret; - helper(s, 4, "", ret); - return ret; - } -}; \ No newline at end of file diff --git a/C_plus/941_ValidMountainArray.cpp b/C_plus/941_ValidMountainArray.cpp deleted file mode 100644 index 6643021..0000000 --- a/C_plus/941_ValidMountainArray.cpp +++ /dev/null @@ -1,78 +0,0 @@ -class Solution -{ -public: - bool validMountainArray(vector &arr) - { - - // option 1 O(n) times - // if(arr.size()<3) return false; - // int l=0, r=arr.size()-1; - // while(l0 && arr[r-1]>arr[r]) r--; - // return (r==arr.size()-1 || l==0)?false:r==l; - - // option 2 O(n) times - // int i=0, n=arr.size(); - // while(iarr[i+1]) i++; - // return i==n-1; - - // option 3 binary search O(nlogn) average time - // [3,5,3,2,0] 會有bug - int n = arr.size(); - if (n < 3) - return false; - - // find 山峰候選點 - int found = binarySearch(arr, 0, n - 1); - // int found = bSearch(arr,n); - cout << found << endl; - if (found == -1) - return false; - - // 驗證其合法性,檢查山峰候選點左右是否有為斜坡單調遞增、單調遞減。 - for (int i = 0; i < found; i++) - { - if (arr[i] >= arr[i + 1]) - { - return false; - } - } - for (int i = n - 1; i > found; i--) - { - if (arr[i] >= arr[i - 1]) - { - return false; - } - } - return true; - } - - int binarySearch(vector &arr, int l, int r) - { - int val, prev, next; - while (l <= r) - { - int mid = l + (r - l) / 2; - cout << mid << endl; - if (mid - 1 >= 0 && mid + 1 < arr.size()) - { - val = arr[mid]; - prev = arr[mid - 1]; - next = arr[mid + 1]; - if (val > prev && val > next) - { - return mid; - } - else if (val > prev && next > val) - l = mid + 1; - else - r = mid; // 防止 [3,5,3,2,0] mid = 2 直接變成0 ,(0+2)/2 = 1 , 而不要使他成為 (0+1)/2=0 - } - else - break; - } - return -1; - } -}; \ No newline at end of file diff --git a/C_plus/949_LargestTimeForGivenDigits.cpp b/C_plus/949_LargestTimeForGivenDigits.cpp deleted file mode 100644 index 73687d7..0000000 --- a/C_plus/949_LargestTimeForGivenDigits.cpp +++ /dev/null @@ -1,24 +0,0 @@ -class Solution -{ -public: - string largestTimeFromDigits(vector &arr) - { - string ret = ""; - for (int i = 0; i < arr.size(); ++i) - { - for (int j = 0; j < arr.size(); j++) - { - for (int k = 0; k < arr.size(); ++k) - { - if (i == j || j == k || k == i) - continue; - string h = to_string(arr[i]) + to_string(arr[j]); - string m = to_string(arr[k]) + to_string(arr[6 - i - j - k]); - if (stoi(h) < 24 && stoi(m) < 60 && (h + ":" + m) > ret) - ret = h + ':' + m;w - } - } - } - return ret; - } -}; \ No newline at end of file diff --git a/C_plus/94_BinaryTreeInorderTraversal.cpp b/C_plus/94_BinaryTreeInorderTraversal.cpp deleted file mode 100644 index bd0c0b5..0000000 --- a/C_plus/94_BinaryTreeInorderTraversal.cpp +++ /dev/null @@ -1,97 +0,0 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution -{ -public: - void inorder(TreeNode *root, vector &ret) - { - if (root) - { - inorder(root->left, ret); - ret.push_back(root->val); - inorder(root->right, ret); - } - } - vector inorderTraversal(TreeNode *root) - { - // option 1 recursive O(n) space - vector ret; - inorder(root, ret); - return ret; - - // option 2 stack+iterative O(n) space - vector ret; - stack sta; - addLeftToStack(sta, root); - - while (!sta.empty()) - { - TreeNode *cur = sta.top(); - sta.pop(); - ret.push_back(cur->val); - addLeftToStack(sta, cur->right); - } - - return ret; - - // option 3 Morris Traversal O(1) space - // 所有原本為空的右子節點指向中序遍歷順序後的那個節點 - - // step 1 如果當前節點的左孩子為空,則輸出當前節點並將右孩子當作當前節點 - // step 2 如果當前左孩子不為空,在當前節點的左子樹中找到當前節點在中序遍歷下的前驅節點 - // a) 如果前驅節點的右孩子為空,將他的右孩子設為當前節點。當前節點更新為當前節點的左子樹 - // b) 如果前驅節點的右孩子為當前節點,將他的右孩子設為空(恢復樹的形狀)。輸出當前節點。當前節點更新為當前節點的右孩子 - // stpe 3 重複step 1 step 2 直到當前節點為空。 - - vector vec; - TreeNode *cur = root, *prev = nullptr; - - while (cur) - { - if (cur->left == nullptr) - { //1 - vec.push_back(cur->val); - cur = cur->right; - } - else - { - // find 前驅點 - prev = cur->left; - while (prev->right != nullptr && prev->right != cur) - { - prev = prev->right; - } - - if (prev->right == nullptr) - { // 2.a - prev->right = cur; - cur = cur->left; - } - else - { /// 2.b - prev->right = nullptr; - vec.push_back(cur->val); - cur = cur->right; - } - } - } - return vec; - } - void addLeftToStack(stack &sta, TreeNode *root) - { - while (root != nullptr) - { - sta.push(root); - root = root->left; - } - } -}; \ No newline at end of file diff --git a/C_plus/95*_UniqueBinarySearchTreesII.cpp b/C_plus/95*_UniqueBinarySearchTreesII.cpp deleted file mode 100644 index cd9d7a6..0000000 --- a/C_plus/95*_UniqueBinarySearchTreesII.cpp +++ /dev/null @@ -1,86 +0,0 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution -{ -public: - vector build(int lo, int hi) - { - //定義:建造 閉區間 [lo, hi] 組成的BST - // base case - if (lo > hi) - { - return {nullptr}; - } - - vector ret; - - // 1. 窮舉root 節點的所有可能 - for (int i = lo; i <= hi; ++i) - { - - // 2. 遞回構造出左右子樹的所有合法BST - vector leftTree = build(lo, i - 1); - vector rightTree = build(i + 1, hi); - - // 3. 給root節點窮舉所有左右子樹的組合 - for (TreeNode *left : leftTree) - { - for (TreeNode *right : rightTree) - { - TreeNode *root = new TreeNode(i); - root->left = left; - root->right = right; - ret.push_back(root); - } - } - } - return ret; - } - vector build(int lo, int hi, vector > > &memo) - { - if (lo > hi) - return {nullptr}; - - if (!memo[lo - 1][hi - 1].empty()) - return memo[lo - 1][hi - 1]; - - vector ret; - - for (int i = lo; i <= hi; ++i) - { - vector leftTree = build(lo, i - 1, memo); - vector rightTree = build(i + 1, hi, memo); - - for (TreeNode *left : leftTree) - { - for (TreeNode *right : rightTree) - { - TreeNode *node = new TreeNode(i); - node->left = left; - node->right = right; - ret.push_back(node); - } - } - } - return memo[lo - 1][hi - 1] = ret; - } - vector generateTrees(int n) - { - // option 1 - // if(n == 0) return {}; - // return build(1, n); - - // option 1.1 memo pattern - vector > > memo(n, vector >(n)); - return build(1, n, memo); - } -}; \ No newline at end of file diff --git a/C_plus/954*_ArrayofDoubledPairs.cpp b/C_plus/954*_ArrayofDoubledPairs.cpp deleted file mode 100644 index dad4b45..0000000 --- a/C_plus/954*_ArrayofDoubledPairs.cpp +++ /dev/null @@ -1,36 +0,0 @@ -class Solution -{ -public: - bool canReorderDoubled(vector &arr) - { - - // 4 -2 2 4 - // -2 -4 2 4 i=0,1 => [1] = 2*[0] - // 1 2 4 8 4 16 - // i=0,1,2 - // 兩兩一組,能不能找到一種組法,使得 兩兩成對,會為2倍關係 - - //. 1 2 4 8 2 16 => 1 2 2 4 8 16 - // - int n = arr.size(); - unordered_map mp; - for (int n : arr) - mp[n]++; - // - vector keys; - for (auto &a : mp) - keys.push_back(a.first); - - // 確保 -4 出現在 -8 之前 - sort(keys.begin(), keys.end(), [](int i, int j) - { return abs(i) < abs(j); }); - - for (int k : keys) - { - if (mp[k] > mp[2 * k]) - return false; - mp[2 * k] -= mp[k]; - } - return true; - } -}; \ No newline at end of file diff --git a/C_plus/96*_UniqueBinarySearchTrees.cpp b/C_plus/96*_UniqueBinarySearchTrees.cpp deleted file mode 100644 index 99bddf2..0000000 --- a/C_plus/96*_UniqueBinarySearchTrees.cpp +++ /dev/null @@ -1,59 +0,0 @@ -class Solution -{ -private: - vector > memo; - -public: - int count(int lo, int hi) - { - // 定義:閉區間 [lo, hi] 的數字組成count(lo, hi) 種BST - if (lo > hi) - return 1; - - // 查備忘錄 - if (memo[lo][hi] != 0) - { - return memo[lo][hi]; - } - - int ret = 0; - for (int i = lo; i <= hi; ++i) - { - int left = count(lo, i - 1); - int right = count(i + 1, hi); - // 左右子树的组合数乘積是 BST 的總數 - ret += left * right; - } - // 存入備忘錄 - memo[lo][hi] = ret; - return ret; - } - int numTrees(int n) - { - // option 1 memo pattern - memo = vector >(n + 1, vector(n + 1)); - - return count(1, n); - - // option 2 math - // Catalan number - // 1 1 2 5 14 42 132 429 1430 從0開始 - // (2n)!/((n+1)!* n!) - // C_{n+1} = \sum{n}{i=0} C_{i}C_{n-i} - - // C_{n} = \sum{n-1}{i=0} C_{i}*C_{n-1-i} - // n = 1, C_{1} = C_{0}*C_{0} = 1 - // n = 2, C_{2} = C_{0}*C_{1} + C_{1}*C_{0} = 2 - // n = 3, C_{3} = C_{0}*C_{2} + C_{1}*C_{1} + C_{2}*C_{0} = 1*2 + 1*1 + 2*1 = 5 - - // vector dp(n+1,0); - // dp[0] = 1; - // dp[1] = 1; - // for(int i=2;i<=n;++i){ - // for(int j = 0;jval != ans) - { - ret = false; - return; - } - traverse(root->left, ans, ret); - traverse(root->right, ans, ret); - } - bool helper(TreeNode *node, int &val) - { - if (!node) - return true; - if (node->val != val) - return false; - return helper(node->left, val) && helper(node->right, val); - } - bool isUnivalTree(TreeNode *root) - { - // option 1 - // int ans = root->val; - // bool ret = true; - // traverse(root, ans, ret); - // return ret; - - // option 1.1 - // return helper(root, root->val); - //option 1.1.1 - if (!root) - return true; - if (root->left && root->left->val != root->val) - return false; - if (root->right && root->right->val != root->val) - return false; - return isUnivalTree(root->left) && isUnivalTree(root->right); - } -}; \ No newline at end of file diff --git a/C_plus/969*_PancakeSorting.cpp b/C_plus/969*_PancakeSorting.cpp deleted file mode 100644 index e51ec75..0000000 --- a/C_plus/969*_PancakeSorting.cpp +++ /dev/null @@ -1,66 +0,0 @@ -class Solution -{ -public: - vector ret; - void sort(vector &arr, int n) - { - - // base case - if (n == 1) - return; - - // 在陣列中前n個元素中挑出最大值及其索引 - int maxCake = 0; - int maxCakeIndex = 0; - for (int i = 0; i < n; i++) - { - if (arr[i] > maxCake) - { - maxCake = arr[i]; - maxCakeIndex = i; - } - } - - // 第一次翻轉,將最大餅翻到最上面 - reverse(arr.begin(), arr.begin() + maxCakeIndex + 1); - // 第二次翻轉,將最大餅翻到做下面 - ret.push_back(maxCakeIndex + 1); - reverse(arr.begin(), arr.begin() + maxCake); - ret.push_back(n); - - sort(arr, n - 1); - } - vector pancakeSort(vector &arr) - { - // vector nums = arr; - // sort(nums.begin(), nums.end()); - // if(nums == arr) return {}; - // option 1 O(n^2) - // recursive - sort(arr, arr.size()); - return ret; - - // iteratively - int n = arr.size(); - for (int i = n; i >= 1; --i) - { - if (i == 1) - continue; - int idx = 0, val = 0; - for (int k = 0; k < i; ++k) - { - if (arr[k] > val) - { - val = arr[k]; - idx = k; - } - } - - reverse(arr.begin(), arr.begin() + idx + 1); - reverse(arr.begin(), arr.begin() + i); - ret.push_back(idx + 1); - ret.push_back(i); - } - return ret; - } -}; \ No newline at end of file diff --git a/C_plus/97*_InterleavingString.cpp b/C_plus/97*_InterleavingString.cpp deleted file mode 100644 index b9c8bac..0000000 --- a/C_plus/97*_InterleavingString.cpp +++ /dev/null @@ -1,45 +0,0 @@ -class Solution -{ -public: - bool isInterleave(string s1, string s2, string s3) - { - - // option 1 - - // s1 s2 長度總和必須為等於 s3長度,所以不等於返回false 。 s1 s2 為空,s3必為空字串 - // 空 d b b c a - //空 t f f f f f - //a t - //a t - //b f - //c f - //c f - - if (s1.size() + s2.size() != s3.size()) - return false; - int n = s1.size(), m = s2.size(); - vector > dp(n + 1, vector(m + 1, false)); - //base case - dp[0][0] = true; - for (int i = 1; i <= n; ++i) - { - if (s1[i - 1] == s3[i - 1]) - dp[i][0] = dp[i - 1][0]; - } - for (int j = 1; j <= m; ++j) - { - if (s2[j - 1] == s3[j - 1]) - dp[0][j] = dp[0][j - 1]; - } - - for (int i = 1; i <= n; ++i) - { - for (int j = 1; j <= m; ++j) - { - dp[i][j] = (dp[i - 1][j] && s1[i - 1] == s3[i - 1 + j]) || (dp[i][j - 1] && s2[j - 1] == s3[j - 1 + i]); - } - } - return dp[n][m]; - // option 2 O(s2.length) space - } -}; \ No newline at end of file diff --git a/C_plus/973_KClosestPointstoOrigin.cpp b/C_plus/973_KClosestPointstoOrigin.cpp deleted file mode 100644 index cbc8d1e..0000000 --- a/C_plus/973_KClosestPointstoOrigin.cpp +++ /dev/null @@ -1,40 +0,0 @@ -class Solution -{ -public: - vector > kClosest(vector > &points, int k) - { - // option 1 priority_queue - priority_queue > q; - vector > ret; - int dis = 0; - for (int i = 0; i < points.size(); ++i) - { - dis = points[i][0] * points[i][0] + points[i][1] * points[i][1]; - q.push(make_pair(dis, i)); - if (i >= k) - q.pop(); - } - while (!q.empty()) - { - - ret.push_back(points[q.top().second]); - q.pop(); - } - return ret; - - // option 2 vector - // vector> res; - // vector>ans; - // int dis = 0; - // for(int i=0;i p=res[i]; - // ans.push_back(points[p.second]); - // } - // return ans; - } -}; \ No newline at end of file diff --git a/C_plus/977*_SquaresofaSortedArray.cpp b/C_plus/977*_SquaresofaSortedArray.cpp deleted file mode 100644 index 340230f..0000000 --- a/C_plus/977*_SquaresofaSortedArray.cpp +++ /dev/null @@ -1,52 +0,0 @@ -class Solution -{ -public: - vector sortedSquares(vector &nums) - { - // option 1 O(nlogn) sorted algorithm - // int n = nums.size(); - // vector ret; - // for(int i:nums) ret.emplace_back(i*i); - // sort(ret.begin(),ret.end()); - // return ret; - - // option 1.1 O(nlogn) time - // sort(nums.begin(), nums.end(), [](int a, int b){ - // return abs(a) ret; - // int l =0,r=n-1; - // while(l<=r){ - // if(pow(nums[l],2) >= pow(nums[r],2)){ - // ret.emplace(ret.begin(), pow(nums[l],2)); - // l++; - // } - // else{ - // ret.emplace(ret.begin(), pow(nums[r],2)); - // r--; - // } - // } - // return ret; - - // option 3 simplify faster option 2 - - int n = nums.size(), l = 0, r = n - 1; - vector ret(n, 0); - for (int i = r; i > -1; i--) - { - if (abs(nums[l]) > abs(nums[r])) - { - ret[i] = nums[l] * nums[l++]; - } - else - ret[i] = nums[r] * nums[r--]; - } - return ret; - } -}; \ No newline at end of file diff --git a/C_plus/98*_ValidateBinarySearchTree.cpp b/C_plus/98*_ValidateBinarySearchTree.cpp deleted file mode 100644 index 460ae77..0000000 --- a/C_plus/98*_ValidateBinarySearchTree.cpp +++ /dev/null @@ -1,71 +0,0 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution -{ -public: - void traverse(TreeNode *root, vector &ret) - { - - if (!root) - return; - - traverse(root->left, ret); - ret.push_back(root->val); - traverse(root->right, ret); - } - - bool isValidBST(TreeNode *root, long min, long max) - { - - if (root == nullptr) - return true; - // V - if (!root->left && root->val <= min) - return false; - if (!root->right && root->val >= max) - return false; - - // L R - return isValidBST(root->left, min, root->val) && isValidBST(root->right, root->val, max); - } - - bool isValidBST(TreeNode *root, TreeNode *min, TreeNode *max) - { - if (root == nullptr) - return true; - // V - if (min && root->val <= min->val) - return false; - if (max && root->val >= max->val) - return false; - - return isValidBST(root->left, min, root) && isValidBST(root->right, root, max); - } - - bool isValidBST(TreeNode *root) - { - - // option 1 O(nlogn) time and O(n) space - - // preorder traverse and insert to vector and then check vector it is ascend - // vector vec; - // traverse(root, vec); - // for(int i=1;i &days, vector &costs) - { - - // 1 4 6 7 8 20 - // inf inf inf inf inf inf inf - //i=1 0 2 inf inf inf inf inf - //i=2 0 2 4 - //i=3 0 2 4 6 - //i=4 0 2 4 6 7 - //i=5 0 2 4 6 7 9 - //i=6 0 2 4 6 7 9 11 - - int n = days.size(); - vector dp(n + 1, 0); - dp[0] = 0; - for (int i = 1; i <= n; ++i) - { - dp[i] = dp[i - 1] + costs[0]; - - for (int j = 1; j <= i; ++j) - { - // j<=i 要加等號,因為可能 7天票價 比1天假票便宜 - // 如果 [i] - [j] 差距小於7天,可以用 j-1天的錢 加上 [j...i] 買一張 七天票即可 - if (days[i - 1] - days[j - 1] < 7) - dp[i] = min(dp[i], dp[j - 1] + costs[1]); - if (days[i - 1] - days[j - 1] < 30) - dp[i] = min(dp[i], dp[j - 1] + costs[2]); - } - // for(int d:dp) cout< > intervalIntersection(vector > &firstList, vector > &secondList) - { - - // 畫圖分析 - // 假設兩個區間 [a1, a2] [b1, b2] - // 情況一:沒交集 例 [3,4] [5,6] - // 情況二之一:有交集,且覆蓋區間 例 [3,6] [2,5] , 交集區間[3, 5] - // 情況二之二:有交集, 例 [1,3] [2,5] , 交集區間[2, 3] - // 情況二之三:有交集,且覆蓋區間 例 [2,5] [3,6] , 交集區間[3, 5] - // 情況二之四:有交集, 例 [2,5] [1,3] , 交集區間[2, 3] - // 假設交集區間為 [c1, c2], c1 = max(a1, b1) , c2 = min(a2, b2),得知這可以大幅簡化 - - vector > ret; - - int n = firstList.size(), m = secondList.size(); - int l = 0, r = 0; - while (l < n && r < m) - { - - vector first = firstList[l]; - vector second = secondList[r]; - if (first[1] < second[0]) - { - l++; - } - else if (second[1] < first[0]) - r++; - else - { - // overlap - ret.push_back({max(first[0], second[0]), min(first[1], second[1])}); - - if (second[1] < first[1]) - r++; - else - l++; - } - } - - return ret; - } -}; \ No newline at end of file diff --git a/C_plus/99*_RecoverBinarySearchTree.cpp b/C_plus/99*_RecoverBinarySearchTree.cpp deleted file mode 100644 index 69931b5..0000000 --- a/C_plus/99*_RecoverBinarySearchTree.cpp +++ /dev/null @@ -1,39 +0,0 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution { -public: - - void traverse(TreeNode *root, vector& list, vector& vals) { - if(!root) return ; - - traverse(root->left, list, vals); - list.push_back(root); - vals.push_back(root->val); - traverse(root->right, list, vals); - - } - void recoverTree(TreeNode* root) { - // option 1 O(n) space - vector list; - vector vals; - traverse(root, list, vals); - sort(vals.begin(), vals.end()); - - for(int i=0;ival = vals[i]; - } - - // option 2 morris traverse - - - } -}; \ No newline at end of file diff --git a/C_plus/990*_SatisfiabilityofEqualityEquations.cpp b/C_plus/990*_SatisfiabilityofEqualityEquations.cpp deleted file mode 100644 index f9720ea..0000000 --- a/C_plus/990*_SatisfiabilityofEqualityEquations.cpp +++ /dev/null @@ -1,87 +0,0 @@ -class UF -{ -private: - int count; - vector parent; - vector size; - -public: - UF(int n) - { - count = n; - parent.reserve(n); - size.reserve(n); - for (int i = 0; i < n; ++i) - { - parent[i] = i; - size[i] = 1; - } - } - int find(int x) - { - - while (parent[x] != x) - { - parent[x] = parent[parent[x]]; - x = parent[x]; - } - return x; - } - void unionSet(int p, int q) - { - int rootP = find(p); - int rootQ = find(q); - if (rootP == rootQ) - return; - - if (size[rootP] > size[rootQ]) - { // 看誰資源多 - parent[rootQ] = rootP; // Q認P為首領 - size[rootP] += size[rootQ]; // P 將Q 資源加入到自己底下 - } - else - { - parent[rootP] = rootQ; - size[rootQ] += size[rootP]; - } - } - bool connected(int p, int q) - { - int rootP = find(p); - int rootQ = find(q); - return rootP == rootQ; - } -}; -class Solution -{ -public: - bool equationsPossible(vector &equations) - { - // 很多使用DFS解決的問題,也可以用union find演算法 解決。 - // 26個字母,各成一派 - UF *uf = new UF(26); - // 讓等式的字母做連通 - for (string eq : equations) - { - if (eq[1] == '=') - { - char x = eq[0]; - char y = eq[3]; - uf->unionSet(x - 'a', y - 'a'); - } - } - - // 檢查不等式關係是否打破 相等關係的連通性 - for (string eq : equations) - { - if (eq[1] == '!') - { - char x = eq[0]; - char y = eq[3]; - if (uf->connected(x - 'a', y - 'a')) - return false; - } - } - return true; - } -}; \ No newline at end of file diff --git a/C_plus/993*_CousinsinBinaryTree.cpp b/C_plus/993*_CousinsinBinaryTree.cpp deleted file mode 100644 index 74829e6..0000000 --- a/C_plus/993*_CousinsinBinaryTree.cpp +++ /dev/null @@ -1,54 +0,0 @@ -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution -{ -public: - bool isCousins(TreeNode *root, int x, int y) - { - - // level order 因為是cousin 必定在同一層 - queue q; - q.push(root); - bool stepX = false, stepY = false; - - while (!q.empty()) - { - int size = q.size(); - for (int i = 0; i < size; ++i) - { - TreeNode *p = q.front(); - q.pop(); - if (p->val == x) - stepX = true; - if (p->val == y) - stepY = true; - if (p->left && p->right) - { - // 檢查是否為兄弟 - int left = p->left->val, right = p->right->val; - if ((left == x) && (right == y) || (left == y) && (right == x)) - return false; - } - - if (p->left) - q.push(p->left); - if (p->right) - q.push(p->right); - } - if (stepX && stepY) - return true; - if (stepX || stepY) - return false; - } - return false; - } -}; \ No newline at end of file diff --git a/C_plus/994*_RottingOranges.cpp b/C_plus/994*_RottingOranges.cpp deleted file mode 100644 index 56eec8e..0000000 --- a/C_plus/994*_RottingOranges.cpp +++ /dev/null @@ -1,47 +0,0 @@ -class Solution -{ -public: - int orangesRotting(vector > &grid) - { - queue > q; - int n = grid.size(), m = grid[0].size(); - int freshLeft = 0; - for (int i = 0; i < n; ++i) - { - for (int j = 0; j < m; ++j) - { - if (grid[i][j] == 1) - freshLeft++; - else if (grid[i][j] == 2) - q.push({i, j}); - } - } - - // (0,-1) (-1,0) (0,1) (1,0) - vector acts = {0, -1, 0, 1}; - int step = 0; - while (!q.empty() && freshLeft > 0) - { - int size = q.size(); - for (int i = 0; i < size; ++i) - { - auto p = q.front(); - q.pop(); - for (int j = 0; j < 4; ++j) - { - int x = p[0] + acts[j % 4], y = p[1] + acts[(j + 1) % 4]; - if (x < 0 || x > n - 1 || y < 0 || y > m - 1 || grid[x][y] != 1) - continue; - grid[x][y] = 2; - q.push({x, y}); - freshLeft -= 1; - } - } - step += 1; - } - if (freshLeft > 0) - return -1; - - return step; - } -}; \ No newline at end of file diff --git a/C_plus/997*_FindtheTownJudge.cpp b/C_plus/997*_FindtheTownJudge.cpp deleted file mode 100644 index 01b1c62..0000000 --- a/C_plus/997*_FindtheTownJudge.cpp +++ /dev/null @@ -1,20 +0,0 @@ -class Solution -{ -public: - int findJudge(int n, vector > &trust) - { - vector ret(n, 0); - for (vector p : trust) - { - ret[p[1] - 1]++; - ret[p[0] - 1]--; - } - - for (int i = 0; i < ret.size(); ++i) - { - if (ret[i] == n - 1) - return i + 1; - } - return -1; - } -}; \ No newline at end of file diff --git a/C_plus/9_PalindromeNumber.cpp b/C_plus/9_PalindromeNumber.cpp deleted file mode 100644 index c1acced..0000000 --- a/C_plus/9_PalindromeNumber.cpp +++ /dev/null @@ -1,19 +0,0 @@ -class Solution -{ -public: - bool isPalindrome(int x) - { - if (x < 0) - return false; - if (x % 10 == 0 && x > 0) - return false; - int tmp = 0; - while (x > tmp) - { - tmp *= 10; - tmp += (x) % 10; - x /= 10; - } - return (tmp == x) || (tmp / 10 == x); - } -}; \ No newline at end of file diff --git a/Codility/Arrays/CyclicRotation.cpp b/Codility/Arrays/CyclicRotation.cpp deleted file mode 100644 index 1e5a5b9..0000000 --- a/Codility/Arrays/CyclicRotation.cpp +++ /dev/null @@ -1,22 +0,0 @@ -// you can use includes, for example: -// #include - -// you can write to stdout for debugging purposes, e.g. -// cout << "this is a debug message" << endl; - -vector solution(vector &A, int K) -{ - // write your code in C++14 (g++ 6.2.0) - // O(n) space and O(n) time - if (A.empty()) - return {}; - int size = A.size(); - vector ret(size, 0); - int k = K % size; - for (int i = 0; i < size; ++i) - { - int j = (size - k + i) % size; - ret[i] = A[j]; - } - return ret; -} diff --git a/Codility/Arrays/CyclicRotation.py b/Codility/Arrays/CyclicRotation.py deleted file mode 100644 index bbf3a41..0000000 --- a/Codility/Arrays/CyclicRotation.py +++ /dev/null @@ -1,17 +0,0 @@ -# you can write to stdout for debugging purposes, e.g. -# print("this is a debug message") - - -def solution(A, K): - # write your code in Python 3.6 - # O(n) space and O(n) time - if not A: - return [] - size = len(A) - - k = K % size - ret = [] - for i in range(size): - ret.append(A[(size - k + i) % size]) - - return ret diff --git a/Codility/Arrays/OddOccurrencesInArray.cpp b/Codility/Arrays/OddOccurrencesInArray.cpp deleted file mode 100644 index d7b89a0..0000000 --- a/Codility/Arrays/OddOccurrencesInArray.cpp +++ /dev/null @@ -1,17 +0,0 @@ -// you can use includes, for example: -// #include - -// you can write to stdout for debugging purposes, e.g. -// cout << "this is a debug message" << endl; - -int solution(vector &A) -{ - // write your code in C++14 (g++ 6.2.0) - - int ret = 0; - for (int a : A) - { - ret ^= a; - } - return ret; -} \ No newline at end of file diff --git a/Codility/Arrays/OddOccurrencesInArray.py b/Codility/Arrays/OddOccurrencesInArray.py deleted file mode 100644 index 6e45701..0000000 --- a/Codility/Arrays/OddOccurrencesInArray.py +++ /dev/null @@ -1,10 +0,0 @@ -# you can write to stdout for debugging purposes, e.g. -# print("this is a debug message") - - -def solution(A): - # write your code in Python 3.6 - ret = 0 - for i in A: - ret = ret ^ i - return ret diff --git a/Codility/BinarySearchAlgorithm/MinMaxDivision.cpp b/Codility/BinarySearchAlgorithm/MinMaxDivision.cpp deleted file mode 100644 index e69de29..0000000 diff --git a/Codility/BinarySearchAlgorithm/NailingPlanks.cpp b/Codility/BinarySearchAlgorithm/NailingPlanks.cpp deleted file mode 100644 index e69de29..0000000 diff --git a/Codility/CaterpillarMethod/ AbsDistinct.cpp b/Codility/CaterpillarMethod/ AbsDistinct.cpp deleted file mode 100644 index cec782e..0000000 --- a/Codility/CaterpillarMethod/ AbsDistinct.cpp +++ /dev/null @@ -1,17 +0,0 @@ -// you can use includes, for example: -// #include - -// you can write to stdout for debugging purposes, e.g. -// cout << "this is a debug message" << endl; - -#include -int solution(vector &A) { - // write your code in C++14 (g++ 6.2.0) - // O(N) or O(N*log(N)) - - set s; - for(int a:A){ - s.insert(abs(a)); - } - return s.size(); -} \ No newline at end of file diff --git a/Codility/CaterpillarMethod/ MinAbsSumOfTwo.cpp b/Codility/CaterpillarMethod/ MinAbsSumOfTwo.cpp deleted file mode 100644 index e38bb42..0000000 --- a/Codility/CaterpillarMethod/ MinAbsSumOfTwo.cpp +++ /dev/null @@ -1,29 +0,0 @@ -// you can use includes, for example: -// #include - -// you can write to stdout for debugging purposes, e.g. -// cout << "this is a debug message" << endl; -#include -int solution(vector &A) { - // write your code in C++14 (g++ 6.2.0) - // O(N * log(N)) - - sort(A.begin(), A.end()); - int n = A.size(); - int l =0 , r = n-1; - // -3 1 4 - // 1 - - // -10 -8 3 4 5 - // 5 3 - int ret = 2e+9; - while(l<=r){ - - ret =min(ret, abs(A[l]+A[r])); - if(abs(A[l]) > abs(A[r])) l++; - else r--; - - } - - return ret; -} \ No newline at end of file diff --git a/Codility/CaterpillarMethod/CountDistinctSlices.cpp b/Codility/CaterpillarMethod/CountDistinctSlices.cpp deleted file mode 100644 index e69de29..0000000 diff --git a/Codility/CaterpillarMethod/CountTriangles.cpp b/Codility/CaterpillarMethod/CountTriangles.cpp deleted file mode 100644 index 3b65eae..0000000 --- a/Codility/CaterpillarMethod/CountTriangles.cpp +++ /dev/null @@ -1,37 +0,0 @@ -// you can use includes, for example: -// #include - -// you can write to stdout for debugging purposes, e.g. -// cout << "this is a debug message" << endl; -#include -#include -int solution(vector &A) -{ - // write your code in C++14 (g++ 6.2.0) - // O(N**2) time - sort(A.begin(), A.end()); - int ret = 0; - int n = A.size(); - vector > v; - for (int i = 0; i < n - 2; ++i) - { - int j = i + 1, k = i + 2; - - while (k < n) - { - if (A[i] + A[j] > A[k]) - { - ret += k - j; - k++; - } - else if (j < k - 1) - j++; - else - { - j++; - k++; - } - } - } - return ret; -} \ No newline at end of file diff --git a/Codility/CountingElements/FrogRiverOne.cpp b/Codility/CountingElements/FrogRiverOne.cpp deleted file mode 100644 index 0c835a0..0000000 --- a/Codility/CountingElements/FrogRiverOne.cpp +++ /dev/null @@ -1,24 +0,0 @@ -// you can use includes, for example: -// #include - -// you can write to stdout for debugging purposes, e.g. -// cout << "this is a debug message" << endl; - -int solution(int X, vector &A) -{ - // write your code in C++14 (g++ 6.2.0) - // 最短多少秒 可以到達 A - // A[3] = 4 , 代表 在 3 這位置,葉子掉落時間為 4 - // 1 3 1 4 2 3 5 4 - // - // O(N) - set s; - - for (int i = 0; i < A.size(); ++i) - { - s.insert(A[i]); - if ((int)s.size() == X) - return i; - } - return -1; -} diff --git a/Codility/CountingElements/MaxCounters.cpp b/Codility/CountingElements/MaxCounters.cpp deleted file mode 100644 index 1e37862..0000000 --- a/Codility/CountingElements/MaxCounters.cpp +++ /dev/null @@ -1,64 +0,0 @@ -// you can use includes, for example: -// #include - -// you can write to stdout for debugging purposes, e.g. -// cout << "this is a debug message" << endl; - -vector solution(int N, vector &A) -{ - // write your code in C++14 (g++ 6.2.0) - // O(n^2) time and O(n) space => run time - int n = A.size(); - vector vec(N, 0); - int mx = 0; - for (int i = 0; i < n; ++i) - { - if (A[i] == N + 1) - { - // max counter - for (int &v : vec) - v = mx; - } - else - { - // increase 1 - vec[A[i] - 1]++; - - mx = max(mx, vec[A[i] - 1]); - } - } - return vec; -} - - - -// you can use includes, for example: -// #include - -// you can write to stdout for debugging purposes, e.g. -// cout << "this is a debug message" << endl; - -vector solution(int N, vector &A) { - // write your code in C++14 (g++ 6.2.0) - // O(n) time and O(n) space - int n = A.size(); - vector vec(N,0); - int mx = 0, lastMax = 0; - for(int i=0;i - -// you can write to stdout for debugging purposes, e.g. -// cout << "this is a debug message" << endl; -#include -int solution(vector &A) -{ - // write your code in C++14 (g++ 6.2.0) - - // option 1 - // O(nlogn) or O(n) time - int n = A.size(); - sort(A.begin(), A.end()); - int c = 1; - for (int i = 0; i < n; ++i) - { - if (A[i] == c) - c++; - while (i < n - 1 && A[i] == A[i + 1]) - i++; - } - - return c; -} diff --git a/Codility/CountingElements/PermCheck.cpp b/Codility/CountingElements/PermCheck.cpp deleted file mode 100644 index 0d60fa1..0000000 --- a/Codility/CountingElements/PermCheck.cpp +++ /dev/null @@ -1,20 +0,0 @@ -// you can use includes, for example: -// #include - -// you can write to stdout for debugging purposes, e.g. -// cout << "this is a debug message" << endl; -#include -int solution(vector &A) -{ - // write your code in C++14 (g++ 6.2.0) - - // O(nlogn) time - sort(A.begin(), A.end()); - - for (int i = 0; i < A.size(); ++i) - { - if (A[i] != i + 1) - return 0; - } - return 1; -} \ No newline at end of file diff --git a/Codility/DynamicProgramming/MinAbsSum.cpp b/Codility/DynamicProgramming/MinAbsSum.cpp deleted file mode 100644 index 82aa0d8..0000000 --- a/Codility/DynamicProgramming/MinAbsSum.cpp +++ /dev/null @@ -1,23 +0,0 @@ -// you can use includes, for example: -// #include - -// you can write to stdout for debugging purposes, e.g. -// cout << "this is a debug message" << endl; - -int sum(vector &A, int i, int s) -{ - if (i == A.size()) - return s; - int l = s + A[i]; - int r = s - A[i]; - return min(abs(sum(A, i + 1, l)), abs(sum(A, i + 1, r))); -} - -int solution(vector &A) -{ - // write your code in C++14 (g++ 6.2.0) - // option 1 brute force O(2^n) - sum(A,0,0); - - -} diff --git a/Codility/DynamicProgramming/NumberSolitaire.cpp b/Codility/DynamicProgramming/NumberSolitaire.cpp deleted file mode 100644 index 4d4f198..0000000 --- a/Codility/DynamicProgramming/NumberSolitaire.cpp +++ /dev/null @@ -1,62 +0,0 @@ -// you can use includes, for example: -// #include - -// you can write to stdout for debugging purposes, e.g. -// cout << "this is a debug message" << endl; -int solution(vector &A) -{ - // write your code in C++14 (g++ 6.2.0) - // O(n) time and O(n) space - // 1 -2 0 9 -1 -2 - - // 1 -1 - // - - // dp[ i] = max(dp[i], dp[i-1] + A[i]); - int n = A.size(); - if (n == 2) - return A[0] + A[1]; - vector dp(n, -1e+5); - dp[0] = A[0]; - for (int i = 1; i < n; ++i) - { - // 當下站在哪個位置 - for (int j = 1; j <= 6 && j <= i; ++j) - { - // j= - dp[i] = max(dp[i], dp[i - j] + A[i]); - } - cout << endl; - } - return dp[n - 1]; -} -// you can use includes, for example: -// #include - -// you can write to stdout for debugging purposes, e.g. -// cout << "this is a debug message" << endl; -int solution(vector &A) -{ - // write your code in C++14 (g++ 6.2.0) - // 1 -2 0 9 -1 -2 - - // 1 -1 - // - - // dp[ i] = max(dp[i], dp[i-1] + A[i]); - int n = A.size(); - if (n == 2) - return A[0] + A[1]; - vector dp(n, -1e+5); - dp[0] = A[0]; - for (int i = 1; i < n; ++i) - { - // 當下站在哪個位置 - for (int j = 1; j <= 6 && j <= i; ++j) - { - // j= - dp[i] = max(dp[i], dp[i - j] + A[i]); - } - } - return dp[n - 1]; -} \ No newline at end of file diff --git a/Codility/EuclideanAlgorithm/ChocolatesByNumbers.cpp b/Codility/EuclideanAlgorithm/ChocolatesByNumbers.cpp deleted file mode 100644 index c41370f..0000000 --- a/Codility/EuclideanAlgorithm/ChocolatesByNumbers.cpp +++ /dev/null @@ -1,34 +0,0 @@ -// you can use includes, for example: -// #include - -// you can write to stdout for debugging purposes, e.g. -// cout << "this is a debug message" << endl; -#include - -int gcd(int a, int b){ - if(a%b==0) return b; - else return gcd(b, a%b); -} - -int solution(int N, int M) -{ - // write your code in C++14 (g++ 6.2.0) - // option 1 O(n) time out - int ret = 0; - vector eaten(N, false); - for (int i = 0; i < N; i = (i + M) % N) - { - - if (!eaten[i]) - { - eaten[i] = true; - ret++; - } - else - break; - } - return ret; - - // option 2 O(log(N + M)) time - return N/gcd(N,M); -} diff --git a/Codility/EuclideanAlgorithm/CommonPrimeDivisors.cpp b/Codility/EuclideanAlgorithm/CommonPrimeDivisors.cpp deleted file mode 100644 index e69de29..0000000 diff --git a/Codility/FibonacciNumbers/FibFrog.cpp b/Codility/FibonacciNumbers/FibFrog.cpp deleted file mode 100644 index e69de29..0000000 diff --git a/Codility/FibonacciNumbers/Ladder.cpp b/Codility/FibonacciNumbers/Ladder.cpp deleted file mode 100644 index e816bc9..0000000 --- a/Codility/FibonacciNumbers/Ladder.cpp +++ /dev/null @@ -1,34 +0,0 @@ -// you can use includes, for example: -// #include - -// you can write to stdout for debugging purposes, e.g. -// cout << "this is a debug message" << endl; - -vector solution(vector &A, vector &B) { - // write your code in C++14 (g++ 6.2.0) - // O(L) time - // dp - // N = 4 - // 0 1 2 3 4 - // 1 1 2 3 5 - - // N = 5 - // 0 1 2 3 4 5 - // 1 1 2 3 5 8 - int n = A.size(); - int mx = 0; - for(int a:A) mx = max(a, mx); - vector dp(mx+1,0); - dp[0] = 1; - dp[1] = 1; - for(int i=2;i<=mx ; ++i) { - // avoid overflow - dp[i] = (dp[i-1] + dp[i-2])% (1<<30); - } - vector ret; - for(int i=0;i - -// you can write to stdout for debugging purposes, e.g. -// cout << "this is a debug message" << endl; -#include -int solution(vector &A, vector &B) -{ - // write your code in C++14 (g++ 6.2.0) - // O(n) - if (A.empty()) - return 0; - int n = A.size(); - int ret = 1; - int start = A[0], end = B[0]; - for (int i = 1; i < n; ++i) - { - if (end < A[i]) - { - ret++; - end = B[i]; - } - } - return ret; -} \ No newline at end of file diff --git a/Codility/GreedyAlgorithms/TieRopes.cpp b/Codility/GreedyAlgorithms/TieRopes.cpp deleted file mode 100644 index e69de29..0000000 diff --git a/Codility/Iteration/BinaryGap.py b/Codility/Iteration/BinaryGap.py deleted file mode 100644 index e9fd02c..0000000 --- a/Codility/Iteration/BinaryGap.py +++ /dev/null @@ -1,33 +0,0 @@ -# you can write to stdout for debugging purposes, e.g. -# print("this is a debug message") - - -def solution(N): - # write your code in Python 3.6 - # O(n) time and O(n) space - # 9 1001 => 2 - # 15 1111 => 0 - # 32 100000 => 0 - # 1041 10000010001 => 5 - - # to string - l = [] - while N: - l.append(N & 1) - N >>= 1 - - l = l[::-1] - - ret = 0 - c = 0 - flag = False - for i in l: - if i == 0: - c += 1 - elif i == 1: - if flag: - ret = max(ret, c) - c = 0 - flag = True - - return ret diff --git a/Codility/Iteration/BinaryGrap.cpp b/Codility/Iteration/BinaryGrap.cpp deleted file mode 100644 index b5143bf..0000000 --- a/Codility/Iteration/BinaryGrap.cpp +++ /dev/null @@ -1,42 +0,0 @@ -// you can use includes, for example: -// #include - -// you can write to stdout for debugging purposes, e.g. -// cout << "this is a debug message" << endl; -#include -#include -int solution(int N) -{ - // write your code in C++14 (g++ 6.2.0) - // O(n) time and O(n) space - - int ret = 0; - bool flag = false; - - vector vec; - // to string - while (N) - { - vec.push_back(N & 1); - N >>= 1; - } - reverse(vec.begin(), vec.end()); - - int c = 0; - for (int i : vec) - { - if (i == 0) - c++; - else - { - if (flag) - { - ret = max(ret, c); - c = 0; - } - flag = true; - } - } - - return ret; -} diff --git a/Codility/Leader/Dominator.cpp b/Codility/Leader/Dominator.cpp deleted file mode 100644 index 5026d33..0000000 --- a/Codility/Leader/Dominator.cpp +++ /dev/null @@ -1,50 +0,0 @@ -// you can use includes, for example: -// #include - -// you can write to stdout for debugging purposes, e.g. -// cout << "this is a debug message" << endl; -#include -int solution(vector &A) -{ - // write your code in C++14 (g++ 6.2.0) - - bool first = true; - int count = -1; - int val = 0; - for (int i = 0; i < A.size(); ++i) - { - if (first) - { - count = 1; - val = A[i]; - first = false; - } - else - { - if (val != A[i]) - { - count--; - if (count == 0) - { - count = 1; - val = A[i]; - } - } - else - count++; - } - } - count = 0; - int idx = -1; - for (int i = 0; i < A.size(); ++i) - { - if (A[i] == val) - { - count++; - idx = i; - } - } - if (count > int(A.size() / 2)) - return idx; - return -1; -} \ No newline at end of file diff --git a/Codility/Leader/EquiLeader.cpp b/Codility/Leader/EquiLeader.cpp deleted file mode 100644 index fe844a4..0000000 --- a/Codility/Leader/EquiLeader.cpp +++ /dev/null @@ -1,57 +0,0 @@ -// you can use includes, for example: -// #include - -// you can write to stdout for debugging purposes, e.g. -// cout << "this is a debug message" << endl; - -int hasDominator(vector &A, int l, int r){ - if(r==l) return A[l]; - - bool first = true; - int count = -1, val = 0; - for(int i=l;i<=r;++i){ - if(first){ - count = 1; - val = A[i]; - first = false; - } - else{ - if(val!=A[i]){ - count--; - if(count==0){ - count = 1; - val = A[i]; - } - } - else count++; - } - } - count = 0; - int idx = -1; - for(int i = l; i<=r ;++i){ - if(A[i]==val){ - count++; - idx =i; - } - } - if(count>(r-l+1)/2) return A[idx]; - return -1; - -} -int solution(vector &A) { - // write your code in C++14 (g++ 6.2.0) - // O(n^2) time and O(n) space => time out - int ret = 0; - int n = A.size(); - for(int i=0;i - -// you can write to stdout for debugging purposes, e.g. -// cout << "this is a debug message" << endl; -#include -int solution(vector &A) -{ - // write your code in C++14 (g++ 6.2.0) - - int n = A.size(); - vector l_max(n, 0), r_max(n, 0); - // 3 2 6 -1 4 5 -1 2 - //l 0 2 8 7 11 16 15 0 - //r 0 16 14 8 9 5 0 0 - - for (int i = 1; i < n - 1; ++i) - { - l_max[i] = max(l_max[i - 1] + A[i], 0); - } - for (int i = n - 2; i > 0; i--) - { - r_max[i] = max(r_max[i + 1] + A[i], 0); - } - int mx = 0; - - for (int i = 1; i < n - 1; i++) - { - mx = max(mx, l_max[i - 1] + r_max[i + 1]); - } - return mx; -} diff --git a/Codility/MaximumSliceProblem/MaxProfit.cpp b/Codility/MaximumSliceProblem/MaxProfit.cpp deleted file mode 100644 index 369a380..0000000 --- a/Codility/MaximumSliceProblem/MaxProfit.cpp +++ /dev/null @@ -1,17 +0,0 @@ -// you can use includes, for example: -// #include - -// you can write to stdout for debugging purposes, e.g. -// cout << "this is a debug message" << endl; - -int solution(vector &A) { - // write your code in C++14 (g++ 6.2.0) - // O(n) time and O(1) space - int mn = 400000, ret = 0; - for(int i=0;i - -// you can write to stdout for debugging purposes, e.g. -// cout << "this is a debug message" << endl; - -int solution(vector &A) -{ - // write your code in C++14 (g++ 6.2.0) - - // 3 2 -6 4 0 - - int local_max = 0, global_max = -1e+6; - for (int i = 0; i < A.size(); ++i) - { - local_max = max(local_max + A[i], A[i]); - if (global_max < local_max) - { - global_max = local_max; - } - } - return global_max; -} diff --git a/Codility/PrefixSums/CountDiv.cpp b/Codility/PrefixSums/CountDiv.cpp deleted file mode 100644 index 54620ab..0000000 --- a/Codility/PrefixSums/CountDiv.cpp +++ /dev/null @@ -1,34 +0,0 @@ -// you can use includes, for example: -// #include - -// you can write to stdout for debugging purposes, e.g. -// cout << "this is a debug message" << endl; - -int solution(int A, int B, int K) -{ - // write your code in C++14 (g++ 6.2.0) - // O(n) time - int count = 0; - if (K == 1) - return B - A + 1; - if (A == B) - return A % K == 0 ? 1 : 0; - - int l = A; - while (l <= B) - { - if (l % K == 0) - { - if ((B - l) % K == 0) - count = (B - l) / K + 1; - else - count = (B - l) / K + 1; - break; - } - else - { - l++; - } - } - return count; -} diff --git a/Codility/PrefixSums/GenomicRangeQuery.cpp b/Codility/PrefixSums/GenomicRangeQuery.cpp deleted file mode 100644 index 8e561fd..0000000 --- a/Codility/PrefixSums/GenomicRangeQuery.cpp +++ /dev/null @@ -1,34 +0,0 @@ -// you can use includes, for example: -// #include - -// you can write to stdout for debugging purposes, e.g. -// cout << "this is a debug message" << endl; -#include -vector solution(string &S, vector &P, vector &Q) -{ - // write your code in C++14 (g++ 6.2.0) - - // brute force O(n^2) => time out - // 2 1 3 2 2 4 1 - // - // - vector ret; - unordered_map mp; - string dna = "ACGT"; - int n = P.size(); - for (int i = 0; i < dna.size(); ++i) - mp[dna[i]] = i + 1; - for (int i = 0; i < n; ++i) - { - - int temp = INT_MAX; - int s = P[i], e = Q[i]; - for (int j = s; j <= e; ++j) - { - char d = S[j]; - temp = min(temp, mp[d]); - } - ret.push_back(temp); - } - return ret; -} diff --git a/Codility/PrefixSums/MinAvgTwoSlice.cpp b/Codility/PrefixSums/MinAvgTwoSlice.cpp deleted file mode 100644 index c73caf0..0000000 --- a/Codility/PrefixSums/MinAvgTwoSlice.cpp +++ /dev/null @@ -1,58 +0,0 @@ -// you can use includes, for example: -// #include - -// you can write to stdout for debugging purposes, e.g. -// cout << "this is a debug message" << endl; -#include -int solution(vector &A) -{ - // write your code in C++14 (g++ 6.2.0) - // option 1 time out - int n = A.size(); - if (n == 2) - return 0; - - vector preSum(n + 1, 0); - for (int i = 0; i < n; ++i) - { - preSum[i + 1] = preSum[i] + A[i]; - } - int ret = -1; - float val = 1e+4; - for (int i = 0; i <= n - 2; ++i) - { - float avg = (preSum[i + 2] - preSum[i]) / 2; - for (int j = i + 2; j <= n; ++j) - { - float total = preSum[j] - preSum[i]; - avg = min(total / (j - i), avg); - } - if (avg < val) - { - val = avg; - ret = i; - } - } - return ret; - - // option 2 最小區間只會存在於兩個是做或是三個數字,因為如果有超過3個數字,代表還可以在拆分 - // O(n) time - int n = A.size(); - double mn = 100000; - int idx = -1; - for (int i = 0; i < n - 1; ++i) - { - if ((double)(A[i] + A[i + 1]) / 2.0 < mn) - { - mn = (double)(A[i] + A[i + 1]) / 2.0; - idx = i; - } - if (i < n - 2 && (double)(A[i] + A[i + 1] + A[i + 2]) / 3.0 < mn) - { - mn = (double)(A[i] + A[i + 1] + A[i + 2]) / 3.0; - idx = i; - } - } - - return idx; -} diff --git a/Codility/PrefixSums/PassingCars.cpp b/Codility/PrefixSums/PassingCars.cpp deleted file mode 100644 index 421b0ec..0000000 --- a/Codility/PrefixSums/PassingCars.cpp +++ /dev/null @@ -1,51 +0,0 @@ -// you can use includes, for example: -// #include - -// you can write to stdout for debugging purposes, e.g. -// cout << "this is a debug message" << endl; - -int solution(vector &A) -{ - // write your code in C++14 (g++ 6.2.0) - - // 0 1 0 1 1 - // (0,1) (0,3) (0,4) (2,3) (2,4) - - // brute force O(n^2) => time out - // int n = A.size(); - // int count = 0; - // int l = 0; - // while (A[l] == 1) - // l++; - // for (int i = l; i < n - 1; ++i) - // { - // if (A[i] == 1) - // continue; - - // for (int j = i + 1; j < n; ++j) - // count += A[j]; - // } - // return count; - - // option 2 O(n) time - - vector vec(n, 0); - int c = 0; - for (int i = n - 2; i > -1; i--) - { - c += A[i + 1]; - vec[i] = c; - } - int count = 0; - for (int i = 0; i < n; ++i) - { - if (A[i] == 0) - { - - count += vec[i]; - if (count > 1e+9) - return -1; - } - } - return count; -} diff --git a/Codility/PrimeandCompositeNumbers/CountFactors.cpp b/Codility/PrimeandCompositeNumbers/CountFactors.cpp deleted file mode 100644 index e69de29..0000000 diff --git a/Codility/PrimeandCompositeNumbers/Flags.cpp b/Codility/PrimeandCompositeNumbers/Flags.cpp deleted file mode 100644 index e69de29..0000000 diff --git a/Codility/PrimeandCompositeNumbers/MinPerimeterRectangle.cpp b/Codility/PrimeandCompositeNumbers/MinPerimeterRectangle.cpp deleted file mode 100644 index 6e1d2e1..0000000 --- a/Codility/PrimeandCompositeNumbers/MinPerimeterRectangle.cpp +++ /dev/null @@ -1,37 +0,0 @@ -// you can use includes, for example: -// #include - -// you can write to stdout for debugging purposes, e.g. -// cout << "this is a debug message" << endl; -#include -vector factor(int N) -{ - - vector factor; - int i; - for (i = 1; i < N / i; ++i) - { - if (N % i == 0) - { - factor.push_back(i); - } - } - if (i * i == N) - factor.push_back(i); - return factor; -} -int solution(int N) -{ - // write your code in C++14 (g++ 6.2.0) - // O(sqrt(n)) - // 面積為 N,求最小周長組合 - // 先求 30 的因數 - vector vec = factor(N); - int ret = 1e+9 * 2; - for (int i : vec) - { - int perimeter = 2 * (i + N / i); - ret = min(ret, perimeter); - } - return ret; -} diff --git a/Codility/PrimeandCompositeNumbers/Peaks.cpp b/Codility/PrimeandCompositeNumbers/Peaks.cpp deleted file mode 100644 index 33a19da..0000000 --- a/Codility/PrimeandCompositeNumbers/Peaks.cpp +++ /dev/null @@ -1,36 +0,0 @@ -// you can use includes, for example: -// #include - -// you can write to stdout for debugging purposes, e.g. -// cout << "this is a debug message" << endl; -#include -int solution(int N) { - // write your code in C++14 (g++ 6.2.0) - - - // option 1 time out - // vector factor(N, false); - // // 1 2 3 4 5 6 7 8 - // // t t f t f f f t - - // for(int i=1;i<=N/2;++i){ - // if( N%i==0){ - // factor[i-1] = true; - // factor[ N/i -1] = true; - // } - // } - // int count = 0; - // for(bool f:factor) count+=f; - // return count; - - // option 2 - if(N==1) return 1; - int ret = 0; - int i; - for(i=1 ; i - -// you can write to stdout for debugging purposes, e.g. -// cout << "this is a debug message" << endl; - -#include -vector solution(vector &A) -{ - // write your code in C++14 (g++ 6.2.0) - - // O(n^2) => time out - - vector ret; - - for (int i = 0; i < A.size(); ++i) - { - // int k = A[i]; - int factor = 0; - for (int j = 0; j < A.size(); ++j) - { - if (A[i] % A[j] != 0) - factor++; - } - - ret.push_back(factor); - } - return ret; -} \ No newline at end of file diff --git a/Codility/SieveofEratosthenes/CountSemiprimes.cpp b/Codility/SieveofEratosthenes/CountSemiprimes.cpp deleted file mode 100644 index e69de29..0000000 diff --git a/Codility/Sorting/Distinct.cpp b/Codility/Sorting/Distinct.cpp deleted file mode 100644 index 648e7a9..0000000 --- a/Codility/Sorting/Distinct.cpp +++ /dev/null @@ -1,16 +0,0 @@ -// you can use includes, for example: -// #include - -// you can write to stdout for debugging purposes, e.g. -// cout << "this is a debug message" << endl; -#include -int solution(vector &A) -{ - // write your code in C++14 (g++ 6.2.0) - // option 1 - // O(n) time and O(n) space - unordered_set s; - for (int a : A) - s.insert(a); - return s.size(); -} diff --git a/Codility/Sorting/MaxProductOfThree.cpp b/Codility/Sorting/MaxProductOfThree.cpp deleted file mode 100644 index d53bc98..0000000 --- a/Codility/Sorting/MaxProductOfThree.cpp +++ /dev/null @@ -1,16 +0,0 @@ -// you can use includes, for example: -// #include - -// you can write to stdout for debugging purposes, e.g. -// cout << "this is a debug message" << endl; -#include -int solution(vector &A) -{ - // write your code in C++14 (g++ 6.2.0) - - // O(nlogn) time - sort(A.begin(), A.end()); - int n = A.size(); - - return max(A[0] * A[1] * A[n - 1], A[n - 3] * A[n - 2] * A[n - 1]); -} diff --git a/Codility/Sorting/NumberOfDiscIntersections.cpp b/Codility/Sorting/NumberOfDiscIntersections.cpp deleted file mode 100644 index e69de29..0000000 diff --git a/Codility/Sorting/Triangle.cpp b/Codility/Sorting/Triangle.cpp deleted file mode 100644 index 79a9bd6..0000000 --- a/Codility/Sorting/Triangle.cpp +++ /dev/null @@ -1,23 +0,0 @@ -// you can use includes, for example: -// #include - -// you can write to stdout for debugging purposes, e.g. -// cout << "this is a debug message" << endl; -#include -int solution(vector &A) { - // write your code in C++14 (g++ 6.2.0) - - // option 1 - // O(NlogN) time - int n = A.size(); - sort(A.begin(), A.end()); - for(int i = 0;i A[i+2] -A[i+1] ){ - // A[i+2] + A[i+2] > A[i] 不用比較,因為排序過了 - // A[i+2] + A[i] > A[i+1] 不用比較,因為排序過了 - return 1; - } - } - return 0; -} diff --git a/Codility/StacksandQueues/Brackets.cpp b/Codility/StacksandQueues/Brackets.cpp deleted file mode 100644 index a210077..0000000 --- a/Codility/StacksandQueues/Brackets.cpp +++ /dev/null @@ -1,34 +0,0 @@ -// you can use includes, for example: -// #include - -// you can write to stdout for debugging purposes, e.g. -// cout << "this is a debug message" << endl; -#include -int solution(string &S) -{ - // write your code in C++14 (g++ 6.2.0) - // O(n) time and O(n) space - stack sta; - for (char c : S) - { - - if (c == '(' || c == '{' || c == '[') - sta.push(c); - - else - { - if (sta.empty()) - return 0; - else if (c == ')' && sta.top() == '(') - sta.pop(); - else if (c == ']' && sta.top() == '[') - sta.pop(); - else if (c == '}' && sta.top() == '{') - sta.pop(); - else - return 0; - } - } - - return sta.empty()?1:0; -} diff --git a/Codility/StacksandQueues/Fish.cpp b/Codility/StacksandQueues/Fish.cpp deleted file mode 100644 index 11f9b0e..0000000 --- a/Codility/StacksandQueues/Fish.cpp +++ /dev/null @@ -1,37 +0,0 @@ -// you can use includes, for example: -// #include - -// you can write to stdout for debugging purposes, e.g. -// cout << "this is a debug message" << endl; - -#include -int solution(vector &A, vector &B) -{ - // write your code in C++14 (g++ 6.2.0) - - stack sta; - int eat = 0; - for (int i = 0; i < A.size(); ++i) - { - if (B[i] == 1) - sta.push(A[i]); - else - { - if (!sta.empty() && sta.top() < A[i]) - { - while (!sta.empty() && sta.top() < A[i]) - { - // 反方向的魚被吃 - eat++; - sta.pop(); - } - } - if (!sta.empty() && sta.top() > A[i]) - { - // 正方向魚被吃 - eat++; - } - } - } - return A.size() - eat; -} diff --git a/Codility/StacksandQueues/Nesting.cpp b/Codility/StacksandQueues/Nesting.cpp deleted file mode 100644 index 6a99717..0000000 --- a/Codility/StacksandQueues/Nesting.cpp +++ /dev/null @@ -1,31 +0,0 @@ -// you can use includes, for example: -// #include - -// you can write to stdout for debugging purposes, e.g. -// cout << "this is a debug message" << endl; -#include -int solution(string &S) -{ - // write your code in C++14 (g++ 6.2.0) - - stack sta; - for (char c : S) - { - if (c == '(' || c == '{' || c == '[') - sta.push(c); - else - { - if (sta.empty()) - return 0; - else if (sta.top() == '(' && c == ')') - sta.pop(); - else if (sta.top() == '[' && c == ']') - sta.pop(); - else if (sta.top() == '{' && c == '}') - sta.pop(); - else - return 0; - } - } - return sta.empty() ? 1 : 0; -} \ No newline at end of file diff --git a/Codility/StacksandQueues/StoneWall.cpp b/Codility/StacksandQueues/StoneWall.cpp deleted file mode 100644 index f689fdd..0000000 --- a/Codility/StacksandQueues/StoneWall.cpp +++ /dev/null @@ -1,24 +0,0 @@ -// you can use includes, for example: -// #include - -// you can write to stdout for debugging purposes, e.g. -// cout << "this is a debug message" << endl; -#include -int solution(vector &H) -{ - // write your code in C++14 (g++ 6.2.0) - stack sta; - // monotonic stack - int ret = 0; - for (int h : H) - { - while (!sta.empty() && sta.top() > h) - { - sta.pop(); - ret++; - } - if (sta.empty() || h > sta.top()) - sta.push(h); - } - return ret + sta.size(); -} \ No newline at end of file diff --git a/Codility/TimeComplexity/FrogJmp.cpp b/Codility/TimeComplexity/FrogJmp.cpp deleted file mode 100644 index c757118..0000000 --- a/Codility/TimeComplexity/FrogJmp.cpp +++ /dev/null @@ -1,14 +0,0 @@ -// you can use includes, for example: -// #include - -// you can write to stdout for debugging purposes, e.g. -// cout << "this is a debug message" << endl; - -int solution(int X, int Y, int D) -{ - // write your code in C++14 (g++ 6.2.0) - if ((Y - X) % D == 0) - return (Y - X) / D; - else - return (Y - X) / D + 1; -} \ No newline at end of file diff --git a/Codility/TimeComplexity/FrogJmp.py b/Codility/TimeComplexity/FrogJmp.py deleted file mode 100644 index eea29f4..0000000 --- a/Codility/TimeComplexity/FrogJmp.py +++ /dev/null @@ -1,9 +0,0 @@ -# you can write to stdout for debugging purposes, e.g. -# print("this is a debug message") - -def solution(X, Y, D): - # write your code in Python 3.6 - if (Y-X)%D==0 : - return int((Y-X)/D) - else: - return int((Y-X)/D +1) \ No newline at end of file diff --git a/Codility/TimeComplexity/PermMissingElem.cpp b/Codility/TimeComplexity/PermMissingElem.cpp deleted file mode 100644 index 16e4e40..0000000 --- a/Codility/TimeComplexity/PermMissingElem.cpp +++ /dev/null @@ -1,25 +0,0 @@ -// you can use includes, for example: -// #include -#include -// you can write to stdout for debugging purposes, e.g. -// cout << "this is a debug message" << endl; - -int solution(vector &A) { - // write your code in C++14 (g++ 6.2.0) - - // option 1 - // int n = A.size(); - // int total = (n+2)*(n+1)/2; - // for(int a:A) total -= a; - // return total; - - // option 2 - int n = A.size(); - int ret = n; - for(int i=0;i - -// you can write to stdout for debugging purposes, e.g. -// cout << "this is a debug message" << endl; -#include - -int solution(vector &A) -{ - // write your code in C++14 (g++ 6.2.0) - // O(n) time and O(n) space - int n = A.size(); - vector sum(n, 0); - // 3 1 2 4 3 - // 13 10 9 7 3 - sum[n - 1] = A[n - 1]; - for (int i = n - 2; i > -1; i--) - { - sum[i] = sum[i + 1] + A[i]; - } - - int ret = INT_MAX, total = 0; - for (int i = 0; i < n - 1; i++) - { - total += A[i]; - ret = min(abs(total - sum[i + 1]), ret); - } - return ret; -} diff --git a/Codility/TimeComplexity/TapeEquilibrium.py b/Codility/TimeComplexity/TapeEquilibrium.py deleted file mode 100644 index e8b040f..0000000 --- a/Codility/TimeComplexity/TapeEquilibrium.py +++ /dev/null @@ -1,22 +0,0 @@ -# you can write to stdout for debugging purposes, e.g. -# print("this is a debug message") - - -def solution(A): - # write your code in Python 3.6 - # O(n) or O(NlogN) time and O(n) space - n = len(A) - sum = [] - sum.append(A[n - 1]) - for i in range(n - 2, -1, -1): - # suminsert(0, sum[0]+A[i]) # O(n) - sum.append(sum[-1] + A[i]) - # reverse - sum = sum[::-1] - # 13 10 9 7 3 - ret = 1e5 - total = 0 - for i in range(n - 1): - total += A[i] - ret = min(abs(total - sum[i + 1]), ret) - return ret diff --git a/Codility/Trainings/ArrayInversionCount.cpp b/Codility/Trainings/ArrayInversionCount.cpp deleted file mode 100644 index aefdb2f..0000000 --- a/Codility/Trainings/ArrayInversionCount.cpp +++ /dev/null @@ -1,87 +0,0 @@ -// you can use includes, for example: -// #include - -// you can write to stdout for debugging purposes, e.g. -// cout << "this is a debug message" << endl; - -vector merge(vector &left, vector &right, int &ans) -{ - vector ret(left.size() + right.size(), 0); - int l = 0, r = 0, k = 0; - int count = 0; - while (l < (int)left.size() && r < (int)right.size()) - { - if (left[l] <= right[r]) - { - ret[k++] = left[l++]; - ans += count; - } - else - { - ret[k++] = right[r++]; - count++; - } - } - while (l < (int)left.size()) - { - ret[k++] = left[l++]; - ans += count; - } - while (r < (int)right.size()) - { - ret[k++] = right[r++]; - } - return ret; -} -vector mergeSort(vector &a, int l, int r, int &ans) -{ - if (l == r) - return {0}; - if (r - l == 1) - return {a[l]}; - - vector left = mergeSort(a, l, (l + r) / 2, ans); - vector right = mergeSort(a, (l + r) / 2, r, ans); - return merge(left, right, ans); -} -int solution(vector &A) -{ - // write your code in C++14 (g++ 6.2.0) - - // O(n^2) timeout - // -1 6 3 4 7 4 - // 0 3 0 0 1 0 - - // [1 2 3] => 0 - // [] => 0 - // dp[i] > dp[j] , dp[i] = dp[j - // base case - // if(A.empty() || A.size()==1) return 0; - // int n = A.size(); - // vector dp(n,0); - // int ret = 0; - // for(int i=n-2;i>-1;i--){ - // for(int j = i+1;j A[j]){ - // dp[i] += +1 ; - - // if(dp[i]> 1e+9) return -1; - // } - // } - // ret += dp[i]; - // } - // return ret; - - // option 2 O(nlogn) merge sort - // base case - // if(A.empty() || A.size()==1) return 0; - // int n = A.size(); - - // -1 6 3 4 7 4 - - int ans = 0; - mergeSort(A, 0, A.size(), ans); - if (ans > 1e+9) - return -1; - return ans; -} diff --git a/Codility/Trainings/DisappearingPairs.cpp b/Codility/Trainings/DisappearingPairs.cpp deleted file mode 100644 index 80af28c..0000000 --- a/Codility/Trainings/DisappearingPairs.cpp +++ /dev/null @@ -1,32 +0,0 @@ -// you can use includes, for example: -// #include - -// you can write to stdout for debugging purposes, e.g. -// cout << "this is a debug message" << endl; -#include -#include -string solution(string &S) -{ - // write your code in C++14 (g++ 6.2.0) - - stack sta; - for (char c : S) - { - if (!sta.empty() && sta.top() == c) - { - sta.pop(); - } - else - { - sta.push(c); - } - } - string ret; - while (!sta.empty()) - { - ret += sta.top(); - sta.pop(); - } - reverse(ret.begin(), ret.end()); - return ret; -} \ No newline at end of file diff --git a/Codility/Trainings/FirstUnique.cpp b/Codility/Trainings/FirstUnique.cpp deleted file mode 100644 index cd017a0..0000000 --- a/Codility/Trainings/FirstUnique.cpp +++ /dev/null @@ -1,26 +0,0 @@ -// you can use includes, for example: -// #include - -// you can write to stdout for debugging purposes, e.g. -// cout << "this is a debug message" << endl; - -#include -int solution(vector &A) -{ - // write your code in C++14 (g++ 6.2.0) - // O(NlogN) time and O(n) space - unordered_map mp; - - int n = A.size(); - int ans = -1; - for (int i = 0; i < n; ++i) - { - mp[A[i]]++; - } - for (int i = 0; i < n; ++i) - { - if (mp[A[i]] == 1) - return A[i]; - } - return ans; -} diff --git a/Codility/Trainings/FloodDepth.cpp b/Codility/Trainings/FloodDepth.cpp deleted file mode 100644 index 3914d61..0000000 --- a/Codility/Trainings/FloodDepth.cpp +++ /dev/null @@ -1,38 +0,0 @@ -// you can use includes, for example: -// #include - -// you can write to stdout for debugging purposes, e.g. -// cout << "this is a debug message" << endl; - -int solution(vector &A) -{ - // write your code in C++14 (g++ 6.2.0) - - // 42. Trapping Rain Water - - // O(n) time and O(n) space for - - // 1 3 2 1 2 1 5 3 3 4 2 - //l 1 3 3 3 3 3 5 5 5 5 5 - //r 5 5 5 5 5 5 5 4 4 4 2 - // 0 0 1 2 1 2 0 1 1 0 0 - int n = A.size(); - vector l_max(n, 0), r_max(n, 0); - l_max[0] = A[0], r_max[n - 1] = A[n - 1]; - for (int i = 1; i < n; ++i) - { - l_max[i] = max(l_max[i - 1], A[i]); - } - for (int i = n - 2; i > -1; i--) - { - r_max[i] = max(r_max[i + 1], A[i]); - } - - int ret = 0; - - for (int i = 0; i < n; ++i) - { - ret = max(min(l_max[i], r_max[i]) - A[i], ret); - } - return ret; -} diff --git a/Codility/Trainings/LongestPassword.cpp b/Codility/Trainings/LongestPassword.cpp deleted file mode 100644 index d416209..0000000 --- a/Codility/Trainings/LongestPassword.cpp +++ /dev/null @@ -1,66 +0,0 @@ -// you can use includes, for example: -// #include - -// you can write to stdout for debugging purposes, e.g. -// cout << "this is a debug message" << endl; -#include - -bool isValid(string &s) -{ - int letter = 0, num = 0; - for (char c : s) - { - // include invalid character - if (isalnum(c) == 0) - return false; - if (isalpha(c) != 0) - letter++; - else if (c - '0' >= 0 && c - '0' <= 9) - num++; - } - return ((letter) % 2 == 0 && (num % 2 != 0)) ? true : false; -} -int solution(string &S) -{ - // write your code in C++14 (g++ 6.2.0) - - vector passwords; - //split words - int n = S.size(); - // special case - if (n == 1) - { - if (S[0] - '0' >= 0 && S[0] - '0' <= 9) - return 1; - return -1; - } - - int i = 0; - while (i < n && S[i] == ' ') - i++; - string word; - while (i < n) - { - if (S[i] == ' ') - { - passwords.push_back(word); - word = ""; - } - else - { - word += S[i]; - } - i++; - } - if (!word.empty()) - passwords.push_back(word); - - int ret = -1; - for (string str : passwords) - { - if (!isValid(str)) - continue; - ret = max(ret, (int)str.size()); - } - return ret; -} diff --git a/Codility/Trainings/ParityDegree.cpp b/Codility/Trainings/ParityDegree.cpp deleted file mode 100644 index 6abc4bd..0000000 --- a/Codility/Trainings/ParityDegree.cpp +++ /dev/null @@ -1,35 +0,0 @@ -// you can use includes, for example: -// #include - -// you can write to stdout for debugging purposes, e.g. -// cout << "this is a debug message" << endl; -#include -#include -#include - -bool isPowerBy2(int n) -{ - return (n > 0 && (n & (n - 1))) == 0; -} -int solution(int N) -{ - // write your code in C++14 (g++ 6.2.0) - - // if(isPowerBy2(N)){ - // return log2(N)-1; - // } - int count = int(log2(double(N))) + 1; - int idx = count - 1; - int ret = 0; - for (int i = count; i > -1; i--) - { - int d = pow(2, idx); - if (N % d == 0) - { - return idx; - // ret = max(ret, i); - } - idx--; - } - return ret; -} \ No newline at end of file diff --git a/Codility/Trainings/ParkingBill.cpp b/Codility/Trainings/ParkingBill.cpp deleted file mode 100644 index 3933b33..0000000 --- a/Codility/Trainings/ParkingBill.cpp +++ /dev/null @@ -1,29 +0,0 @@ -// you can use includes, for example: -// #include - -// you can write to stdout for debugging purposes, e.g. -// cout << "this is a debug message" << endl; - -int solution(string &E, string &L) -{ - // write your code in C++14 (g++ 6.2.0) - int cost = 5; - // 未滿一小時 - if (E[0] == L[0] && E[1] == L[1]) - return cost; - - // - - int ehour = 10 * (E[0] - '0') + (E[1] - '0'); - int lhour = 10 * (L[0] - '0') + (L[1] - '0'); - int hour = (lhour - ehour + 24) % 24; - // cout< 0) - return cost + hour * 4; - return cost + (hour - 1) * 4; -} diff --git a/Codility/Trainings/SlalomSkiing.cpp b/Codility/Trainings/SlalomSkiing.cpp deleted file mode 100644 index 0f4a48c..0000000 --- a/Codility/Trainings/SlalomSkiing.cpp +++ /dev/null @@ -1 +0,0 @@ -// 二分查找算法 + 动态规划,计算最长的递增子序列 \ No newline at end of file diff --git a/Codility/Trainings/StrSymmetryPoint.cpp b/Codility/Trainings/StrSymmetryPoint.cpp deleted file mode 100644 index bf3854b..0000000 --- a/Codility/Trainings/StrSymmetryPoint.cpp +++ /dev/null @@ -1,60 +0,0 @@ -// you can use includes, for example: -// #include - -// you can write to stdout for debugging purposes, e.g. -// cout << "this is a debug message" << endl; - -bool isValid(string &l, string &r) -{ - int i = 0, j = l.size() - 1; - while (i < j) - { - swap(l[i], l[j]); - i++; - j--; - } - return l == r; -} -int solution(string &S) -{ - // write your code in C++14 (g++ 6.2.0) - // option 1 O(n^2) time out - // if (S.empty()) - // return 0; - // if (S.size() == 1) - // return 0; - // if (S.size() == 2) - // return 0; - // // racecar - // // [i,n-1] 是否為回文 - // int ans = 2e+6, n = S.size(); - // for (int i = 1; i < n - 1; ++i) - // { - // string left = S.substr(0, i); - // string right = S.substr(i + 1, (n - 1) - (i + 1) + 1); - - // if (isValid(left, right)) - // { - // ans = min(ans, i); - // } - // } - // return ans; - - // option 2 O(sqrt(n)) time - - if (S.empty()) - return -1; - - int n = S.size(); - if (n % 2 == 0) - // 發生在長度為奇數 - return -1; - int ans = n / 2; - - for (int i = ans, j = ans; j > -1 && i < n; i++, j--) - { - if (S[i] != S[j]) - return -1; - } - return ans; -} \ No newline at end of file diff --git a/Codility/Trainings/TennisTournament.cpp b/Codility/Trainings/TennisTournament.cpp deleted file mode 100644 index 5dba97b..0000000 --- a/Codility/Trainings/TennisTournament.cpp +++ /dev/null @@ -1,12 +0,0 @@ -// you can use includes, for example: -// #include - -// you can write to stdout for debugging purposes, e.g. -// cout << "this is a debug message" << endl; - -int solution(int P, int C) -{ - // write your code in C++14 (g++ 6.2.0) - - return min(C, P / 2); -}w \ No newline at end of file diff --git a/Codility/Trainings/ThreeLetters.cpp b/Codility/Trainings/ThreeLetters.cpp deleted file mode 100644 index a6fc2e7..0000000 --- a/Codility/Trainings/ThreeLetters.cpp +++ /dev/null @@ -1,49 +0,0 @@ -// you can use includes, for example: -// #include - -// you can write to stdout for debugging purposes, e.g. -// cout << "this is a debug message" << endl; -#include -#include -#include -bool canAdd(string &str, char x) -{ - if (str.size() < 2) - return true; - if (str.back() != x) - return true; - if (str[str.size() - 2] != x) - return true; - return false; -} -string solution(int A, int B) -{ - // write your code in C++14 (g++ 6.2.0) - - // 在保证没有连续三个字符相等的情况下,不停地从 a, b 中优先使用剩余次数最多的那个字符添加到结果 res 中 - vector > f = {{A, 'a'}, {B, 'b'}}; - - // int total = A+B; - - string ans; - for (int _ = 0; _ < A + B; ++_) - { - // - sort(f.begin(), f.end()); - reverse(f.begin(), f.end()); - for (auto &k : f) - { - char ch = k.second; - // cout< 0 && canAdd(ans, ch)) - { - ans += ch; - // f[ch]--; - k.first--; - break; - } - } - } - // cout< - -// you can write to stdout for debugging purposes, e.g. -// cout << "this is a debug message" << endl; - -int height(tree *root) -{ - if (!root) - return 0; - if (!root->l && !root->r) - return 0; - return 1 + max(height(root->l), height(root->r)); -} -int solution(tree *T) -{ - // write your code in C++14 (g++ 6.2.0) - if (!T) - return 0; - return height(T); -} diff --git a/Codility/readme.md b/Codility/readme.md deleted file mode 100644 index 265cf87..0000000 --- a/Codility/readme.md +++ /dev/null @@ -1,59 +0,0 @@ - - - - - -Prefix Sum -[62%] GenomicRangeQuery - -Sorting -[0%] NumberOfDiscIntersections - -Leader -[55%] EquiLeader - -Maximum slice problem -* MaxDoubleSliceSum - - -Prime and composite numbers -[0%] Flags -[45%] Your score on this taskPeaks - - - -Sieve of Eratosthenes -[66%] CountNonDivisible -* CountSemiprimes - -Euclidean algorithm -* ChocolatesByNumbers -* CommonPrimeDivisors - -Fibonacci numbers -* FibFrog -* Ladder - -Binary search algorithm -*MinMaxDivision -*NailingPlanks - -Caterpillar method -*CountDistinctSlices - -Greedy algorithms -*TieRopes - -Dynamic programming -[54%] MinAbsSum -[75%] NumberSolitaire - -Trainings -- Algorithm skills -*PolygonConcavityIndex - -- Indeed Prime 2015 challenge -[0%] SlalomSkiing -- Indeed Prime 2016 challenge - -- Indeed Prime 2016 College Coders challenge \ No newline at end of file diff --git a/Cracking-the-coding-interview-part1.md b/Cracking-the-coding-interview-part1.md deleted file mode 100644 index 37d5212..0000000 --- a/Cracking-the-coding-interview-part1.md +++ /dev/null @@ -1,2418 +0,0 @@ -# Cracking the coding interview part 1 - - -###### tags: `interview` `algorithm` - - - -[toc] - - -## Array and Strings - - - - - - -##### **Is Unique**: Implement an algorithm to determine if a string has all unique characters. What if you cannot use additional data structures? -assume ASCII string not Unicode string -```java -boolean isUniqueChars(String str){ - if(str.length()>128) return false; - - boolean[] char_set = new boolean[128]; - - for(int i =0;i0) return false; - checker |= (1<=0;i--){ - if(str[i]==' '){ - str[index-1] = '0'; - str[index-2] = '2'; - str[index-3] = '%'; - index = index - 3; - } - else{ - str[index-1] = sre[i]; - index--; - } - } -} - -``` -```cpp -string replaceSpaces(string str, int trueLength){ - int splaceCount = 0, index , i = 0; - for(i = 0;i=0;i--){ - if(str[i]==' '){ - ret ="20%" + ret; - index = index - 3; - } - else{ - ret = str[i]+ret; - index--; - } - } - return ret; -} - -``` - - - - - - - - -##### **Palindrome Permutation**: Given a string, write a function to check if it is a permutation of a palin­ drome. A palindrome is a word or phrase that is the same forwards and backwards. A permutation is a rearrangement of letters. The palindrome does not need to be limited to just dictionary words. - -1. use a hash table to count how many times each character appears. - - -```java -EXAMPLE -Input: Tact Coa -Output: True (permutations: "taco cat'; "atc o eta·; etc.) -``` - - -- Leetcode 125. Valid Palindrome - - - - -##### **One Away**: There are three types of edits that can be performed on strings: insert a character, remove a character, or replace a character. Given two strings, write a function to check if they are one edit (or zero edits) away. - - -```java -EXAMPLE -pale, ple true -pales, pale -> true -pale, bale -> true -pale, bae -> false - -``` - - - - -##### **String Compression**: Implement a method to perform basic string compression using the counts of repeated characters. For example, the string aabcccccaaa would become a2blc5a3. If the "compressed" string would not become smaller than the original string, your method should return the original string. You can assume the string has only uppercase and lowercase letters (a - z). -- leetcode 443. String Compression -- option 1 At each iteration, check if the current character is the same as the next character. If not, add its compressed version to the result. O(p+k^2) - -```cpp -class Solution { -public: - int compress(vector& chars) { - // At each iteration, check if the current character is the same as the next character. If not, add its compressed version to the result. - int ret = 0; - string str = ""; - int countConsecutive = 0; - for(int i=0;i=chars.size() || chars[i]!=chars[i+1]){ - if(countConsecutive>1) str += chars[i] + to_string(countConsecutive); - else str += chars[i]; - - countConsecutive = 0; - } - - } - cout<(str.begin(), str.end()); - return str.size(); - } -}; -``` - - - - - -##### **Rotate Matrix**: Given an image represented by an NxN matrix, where each pixel in the image is 4 bytes, write a method to rotate the image by 90 degrees. Can you do this in place? - -- 48. Rotate Image - -```cpp -class Solution { -public: - void rotate(vector>& matrix) { - - // option 1 O(n^2) - if (matrix.size() == 0 || matrix[0].size()==0) return; - int n= matrix.size(); - for (int layer = 0; layer < n / 2; layer++){ - int first= layer; - int last= n - 1 - layer; - for(int i = first; i < last; i++) { - int offset = i - first; - - int top= matrix[first][i]; // save top - - // left -> top - matrix[first][i] = matrix[last-offset][first]; - // bottom -> left - matrix[last-offset][first] = matrix[last][last - offset]; - // right-> bottom - matrix[last][last-offset] = matrix[i][last]; - // top -> right - matrix[i][last] =top; - - } - } - } -}; -``` - - -##### **Zero Matrix**: Write an algorithm such that if an element in an MxN matrix is 0, its entire row and column are set to 0. - -- Leetcode 73. Set Matrix Zeroes -```cpp -class Solution { -public: - void setZeroes(vector>& matrix) { - - vector> collect ; - int m = matrix.size(), n = matrix[0].size(); - for(int i=0;i0 &&a==goal.size() ){ - if(s.find(goal) != std::string::npos) return true; - } - return false; - - } -``` - -## Linked Lists - - - -快慢指針技巧,適合用在未知大小串列 - -##### **Remove Duplicate**: Write code to remove duplicates from an unsorted linked list .How would you solve this problem if a temporary buffer is not allowed? - -- leetcode 82 83 - - -```cpp -class Solution { -public: - ListNode* deleteDuplicates(ListNode* head) { - // option 1 O(nlogn) time O(s) space - // 1. 儲存重複節點的值 - // 2. 建立一個新的list 比較是否重複節點,不是則加入新串列 -// if(!head) return head; -// ListNode *ret = new ListNode(-101); -// set s; -// ListNode *p = head; -// while(p->next){ -// if(p->val ==p->next->val) s.insert(p->val); -// p=p->next; -// } -// p=ret; -// ListNode *cur = head; -// while(cur){ -// if(s.find(cur->val)==s.end() ) { -// p->next = new ListNode(cur->val); -// p=p->next; - -// } -// cur=cur->next; -// } -// return ret->next; - - - // option 2 O(n^2) time O(1) space - if(!head || !head->next) return head; - ListNode *ret = new ListNode(-1), *p = ret; - ret->next = head; - while(p->next){ - ListNode *run =p->next; - while(run->next && run->next->val ==run->val){ - run = run->next; - } - if(run==p->next) p=p->next; - else p->next=run->next; - } - return ret->next; - } -}; -``` - -##### **Return Kth to Last**: Implement an algorithm to find the kth to last element of a singly linked list. - -- Leetcode 19. Remove Nth Node From End of List - - -##### **Delete Middle Node**: Implement an algorithm to delete a node in the middle (i.e., any node but the first and last node, not necessarily the exact middle) of a singly linked list, given only access to that node. - -- Leetcode 19. Remove Nth Node From End of List - - -##### **Partition**: Write code to partition a linked list around a value x, such that all nodes less than x come before all nodes greater than or equal to x. If x is contained within the list, the values of x only need to be after the elements less than x (see below). The partition element x can appear anywhere in the "right partition"; it does not need to appear between the left and right partitions. - -- Leetcode 86. Partition List - -##### **Sum Lists**: You have two numbers represented by a linked list, where each node contains a single digit.The digits are stored in reverse order, such that the 1 's digit is at the head of the list. Write a function that adds the two numbers and returns the sum as a linked list. - -- Leetcode 2. 445. Add Two Numbers II - - -#### **Palindrome**: Implement a function to check if a linked list is a palindrome. - - -- Leetcode 234. Palindrome Linked List - - -##### **Intersection**: Given two (singly) linked lists, determine if the two lists intersect. Return the inter­ secting node. Note that the intersection is defined based on reference, not value.That is, if the kth node of the first linked list is the exact same node (by reference) as the jth node of the second linked list, then they are intersecting. - -- Leetcode 160. Intersection of Two Linked Lists - - - - - -##### **Loop Detection**: Given a circular linked list, implement an algorithm that returns the node at the beginning of the loop. - - -- 141. Linked List Cycle -- 142. Linked List Cycle II - -### Stacks and Queues - -queue 常用在BFS或 實作cache - - - -##### **Three in One**: Describe how you could use a single array to implement three stacks. - -Approach 1: Fixed Division -- divide the array in three equal parts and allow the individual stack to grow in that limited space. -- similar design stack -- use array to implement array push pop top isEmpty isFull - - -Approach 2: Flexible Divisions -- allow the stack blocks to be flexible in size. - - - -##### **Stack Min:** How would you design a stack which, in addition to push and pop, has a function min which returns the minimum element? Push, pop and min should all operate in 0(1) time. - -- Leetcode 155. Min Stack - - - -##### **Stack of Plates**: Imagine a (literal) stack of plates. If the stack gets too high, it might topple. Therefore, in real life, we would likely start a new stack when the previous stack exceeds some threshold. Implement a data structure SetOfStacks that mimics this. SetO-fStacks should be composed of several stacks and should create a new stack once the previous one exceeds capacity.SetOfStacks. push() and SetOfStacks. pop() should behave identically to a single stack (that is, pop() should return the same values as it would if there were just a single stack).Implement a function popAt(int index)which performs a pop operation on aspecific sub-stack. - - -##### **Queue via Stacks**: Implement a MyQueue class which implements a queue using two stacks. -- Leetcode 225. Implement Stack using Queues -- Leetcode 232. Implement Queue using Stacks - - -##### **Sort Stack**: Write a program to sort a stack such that the smallest items are on the top. You can use an additional temporary stack, but you may not copy the elements into any other data structure (such as an array). The stack supports the following operations: push, pop, peek, and isEmpty. - - - -##### **Animal Shelter**: An animal shelter, which holds only dogs and cats, operates on a strictly"first in, first out" basis. People must adopt either the"oldest" (based on arrival time) of all animals at the shelter, or they can select whether they would prefer a dog or a cat (and will receive the oldest animal of that type). They cannot select which specific animal they would like. Create the data structures to maintain this system and implement operations such as enqueue, dequeueAny, dequeueDog, and dequeueCat. You may use the built-in Linked list data structure. - - -## Trees and Graph -recursive -- pre-order and other forms of tree traversal are a form of DFS -- assumption that BFS is recursive. -- BFS that has an iterative solution involving a queue usually works best. -- Bidirectional Search operates by essentially running two simultaneous breadth-first searches. - - -##### **Route Between Nodes**: Given a directed graph, design an algorithm to find out whether there is a route between two nodes - -```java -enum State { Unvisited, Visited, Visiting; } -boolean search(Graph g, Node start, Node end) { - if (start == end) return true; - // operates as Queue - LinkedList q = new Linkedlist(); - for (Node u : g.getNodes()) { - u.state = State.Unvisited; - } - start.state = State.Visiting; - q.add(start); - Node u; - while (!q.isEmpty()) { - u = q.removeFirst(); II i.e., dequeue() - if (u != null) { - for (Node v : u.getAdjacent()) { - if (v.state == State.Unvisited) { - if (v == end) { - return true; - } - else { - v.state = State.Visiting; - q.add(v); - } - } - } - u.stateState.Visited; - } - } - return false; -} -``` - -##### **Minimal Tree**: Given a sorted (increasing order) array with unique integer elements, write an algorithm to create a binary search tree with minimal height. - -- Leetcode 108. Convert Sorted Array to Binary Search Tree -```cpp -/** - * Definition for a binary tree node. - * struct TreeNode { - * int val; - * TreeNode *left; - * TreeNode *right; - * TreeNode() : val(0), left(nullptr), right(nullptr) {} - * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} - * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} - * }; - */ -class Solution { -public: - TreeNode* sortedArrayToBST(vector& nums) { - if(nums.empty()) return nullptr; - int mid = nums.size()/2; - TreeNode *root = new TreeNode(nums[mid]); - vector left(nums.begin(), nums.begin()+mid); - vector right(nums.begin()+mid+1, nums.end()); - root->left = sortedArrayToBST(left); - root->right = sortedArrayToBST(right); - return root; - - } -}; -``` - -##### **List of Depths**: Given a binary tree, design an algorithm which creates a linked list of all the nodes at each depth (e.g., if you have a tree with depth D, you'll have D linked lists). - -- Leetcode 104. Maximum Depth of Binary Tree -- Leetcode 111. Minimum Depth of Binary Tree -- Leetcode 109. Convert Sorted List to Binary Search Tree -- Leetcode 114. Flatten Binary Tree to Linked List - - - -```cpp -int maxDepth(TreeNode* root) { - if(!root) return 0; - return 1+max(maxDepth(root->left), maxDepth(root->right)); - } -``` - - -```cpp -int minDepth(TreeNode* root) { - if(!root) return 0; - if(!root->left) return 1+minDepth(root->right); - if(!root->right) return 1+minDepth(root->left); - return 1+min(minDepth(root->left), minDepth(root->right)); - } - -``` - -```cpp - -TreeNode* sortedListToBST(ListNode* head) { - // 先決定root,再分兩部分left, right - if(!head) return nullptr; - // use slow fast to determine root node - ListNode *slow = head, *fast = head, *pre= nullptr; - - while(fast && fast->next){ - pre = slow; - slow = slow->next; - fast = fast->next->next; - } - // partition - if(pre!=nullptr) pre->next = nullptr; - else head = nullptr; - TreeNode *root = new TreeNode(slow->val); - root->left = sortedListToBST(head); - root->right = sortedListToBST(slow->next); - return root; - - } - -``` - - - -##### **Check Balanced**: Implement a function to check if a binary tree is balanced. For the purposes of this question, a balanced tree is defined to be a tree such that the heights of the two subtrees of any node never differ by more than one. - -- Leetcode 110. Balanced Binary Tree -- Leetcode 1382. Balance a Binary Search Tree - - -```cpp - -int getHeight(TreeNode *root){ - if(!root) return 0; - return 1+max(getHeight(root->left), getHeight(root->right)); - } - int checkHeight(TreeNode* root){ - if (root == nullptr) return -1; - int leftHeight = checkHeight(root->left); - if (leftHeight ==INT_MIN) return INT_MIN; // Pass error up - int rightHeight = checkHeight(root->right); - if (rightHeight == INT_MIN) return INT_MIN; // Pass error up - - // What do we use for an error code? The height of a null tree is generally defined to be -1, so that's not a great idea for an error code. Instead, we' ll use Integer. MIN_VALUE. - int heightDiff = leftHeight - rightHeight; - if(heightDiff>1) return INT_MIN; - else return max(leftHeight, rightHeight)+1; - } - - - - - - bool isBalanced(TreeNode* root) { - // option 1 O(N log N) time - // 1. get left child tree hight and right child tree height - // if(!root) return true; - // int heightDiff = getHeight(root->left) - getHeight(root->right); - // if(abs(heightDiff)>1 )return false; - // else return isBalanced(root->left) && isBalanced(root->right); - - // option 2 O(N) time and O(Height) space - return checkHeight(root) != INT_MIN; - - - } - - -``` - - - - - - - - -##### **Validate BST**: Implement a function to check if a binary tree is a binary search tree. - -Traversal issue -- Leetcode 94. Binary Tree Inorder Traversal -- Leetcode 144. Binary Tree Preorder Traversal -- Leetcode 145. Binary Tree Postorder Traversal - - - -- Solution #1: In-Order Traversal - - 用array 按照in-order拜訪順序去儲存原先的tree。並判斷array 是否為遞增,若否,則該BST為無效BST - - 也可以簡化不用array,因為一次只比較array的兩個值。 -- Solution #2: The Min / Max Solution - - -```java -int index = 0; -void copyBST(TreeNode root, int[] array) { - if(root==null) return ; - copyBST(root.left, array); - array[index] = root.data; - index++; - copyBST(root.right, array); - -} -boolean checkBST(TreeNode root) { - int [] array = new ont[root.size]; - - copyBST(root, array); - - - for(int i=1;iarray[i] ) return false; - } - return true; -} - -``` - - -```java -Integer last_printed = null; - -boolean checkBST(TreeNode n) { - if(n==null) return true; - - // Check recurse left - if (!checkBST(n.left)) return false; - - // Check current - if (last_printed != null && n.data =< last_printed){ - return false; - } - - last_printed = n.data; - - // Check recurse right - if (!checkBST(n.right)) return false; - - return true; - - - -} - - -``` - -```java -// O(n) time and O(logN) space -boolean checkBST(TreeNode n) { - - return checkBST(n, null, null); -} - -boolean checkBST(TreeNode n, Integer min, Intefet max){ - if(n==null) return true; - - - // check this level - if( (min!=null && n.data<=min) || (max!=null && n.data>max) ){ - return false; - } - - // check left child and right child - if(!checkBST(n.left, min, n.data) || !checkBST(n.right, n.data, max)){ - return false; - } - - - - return true; -} -``` - -##### **Successor**: Write an algorithm to find the "next" node (i.e., in-order successor) of a given node in a binary search tree. You may assume that each node has a link to its parent. - -- Leetcode 285. Inorder Successor in BST -- Leetcode 510. Inorder Successor in BST II - - -pseudcode - -```cpp -Node inorderSucc(Node n){ - if(n has a right subtree){ - return leftmost child of right subtree; - } - else{ - while (n is a right child of n.parent){ - n = n.parent; // Go up - } - return n.parent; - } -} - -``` - -```java -TreeNode inorderSucc(TreeNode n) { - if(n==null) return null; - if(n.right!=null){ - return leftMostChild(n.right); - } - else{ - TreeNode q = n; - TreeNode x = q.parent; - while( x!=null && x.left=q){ - q = x; - x = x.parent; - } - return x; - } - - -} - - -TreeNode leftMostChild(TreeNode n){ - if(n==null) return null; - - while(n.left!=null){ - n=n.left; - } - return n; -} - -``` - - -```cpp -Node* inorderSuccessor(Node* node) { - if (!node) return nullptr; - Node *res = nullptr; - if (node->right) { - res = node->right; - while (res && res->left) res = res->left; - } else { - res = node->parent; - while (res && res->val < node->val) res = res->parent; - } - return res; - -``` - -##### **Build Order**: You are given a list of projects and a list of dependencies (which is a list of pairs of projects, where the second project is dependent on the first project). All of a project's dependencies must be built before the project is. Find a build order that will allow the projects to be built. If there is no valid build order, return an error. - - - -##### **First Common Ancestor**: Design an algorithm and write code to find the first common ancestor of two nodes in a binary tree. Avoid storing additional nodes in a data structure. NOTE: This is not necessarily a binary search tree. - -- Leetcode 235. Lowest Common Ancestor of a Binary Search Tree -- Leetcode 236. Lowest Common Ancestor of a Binary Tree - - -- Solution #1: With Links to Parents -- Solution #2: With Links to Parents (Better Worst-Case Runtime) -- Solution #3: Without Links to Parents -- Solution #4: Optimized - -```java -// O(d) time, d is the depth of the deeper node. -TreeNode * commonAncestor(TreeNode p, TreeNode q){ - int delta = depth(p)- depth(q); - TreeNode first = delta>0?q:p; // get shallower node - TreeNode second = delta>0?p:q; // get deeper node - - second = goUpBy(second, Math.abs(delta)); - /* Find where paths intersect. */ - while(first !=second && first!=null && second !=null){ - first = first.parent; - second = second.parent; - } - return first==null || second == null ? null:first; - -} -TreeNdoe goUpBy(TreeNode node , int delta){ - while(delta >0 && node!=null){ - node = node.parent; - delta--; - } - return node; -} -int depth(TreeNode node){ - int depth = 0; - while(node !=null){ - node = node.parent; - depth++; - } - return depth; -} -``` - -```java -// O(t) time , t is the size of the subtree for the first common ancestor - -TreeNode commonAncestor(TreeNode root, TreeNOde p, TreeNode q){ - if(!covers(root, p) || !covers(root, q)){ - return null; - } - else if( covers(p,q)) return p; - else if (covers(q,p)) return q; - TreeNode sibling = getSibling(p); - TreeNode parent = p.parent; - while(!covers(sibling, q)){ - sibling = getSibling(parent); - parent = parent.parent; - } - return parent; -} -bool covers(TreeNode root, TreeNode p){ - if(root == null) return false; - if( root==p ) return true; - return covers(root.left, p) || covers(root.right, p); -} -TreeNode getSibling(TreeNode node){ - if(node==null || node.parent = null ) return null; - TreeNode parent = node.parent; - return parent.left ==node ?parent.right :parent.left; -} -``` - - -```java - -TreeNode commonAncestor(TreeNode root, TreeNOde p, TreeNode q){ - if(!covers(root, p) || !covers(root, q)){ - return null; - } - - return ancestorHelper(root, p, q); - -} - -TreeNode ancestorHelper(TreeNode root, TreeNOde p, TreeNode q){ - if(root ==null || root==p || root==q){ - return root; - } - - boolean pIsOnLeft = covers(root.left, p); - boolean qIsOnLeft = covers(root.left, q); - if(pIsOnLeft !=qIsOnLeft) return root; - - TreeNode childSide = pIsOnLeft?root.left:root.right; - return ancestorHelper(childSide, p, q); - - -} -bool covers(TreeNode root, TreeNode p){ - if(root == null) return false; - if( root==p ) return true; - return covers(root.left, p) || covers(root.right, p); -} -``` - - -```java -class Result{ - public TreeNode node; - public boolean isAncestor; - public Result(TreeNode n , boolean isAnc){ - node = n; - isAncestor =isAnc; - } -} -TreeNode commonAncestor(TreeNode root, TreeNode p, TreeNode q){ - Result r = commonAncestorHelper(root,p,q); - if(r.isAncestor){ - return r.ndoe; - } - return null; - } - -} - -Result commonAncestorHelper(TreeNode root, TreeNode p, TreeNode q){ - if(root==null) return new Result(null, false); - if(root==p || root==q){ - return new Result(root, true); - } - - Result rx = commonAncestorHelper(root.left, p, q); - if(ry.isAncestor){ - return ry; - } - - if(rx.node !=null && ry.node !=null){ - return new Result(root, true); - } - else if(root ==p || root==q){ - boolean isAncestor = rx.node !=null || ry.node==null; - return new Rsult(root, isAncestor); - } - else{ - return new Result(rx.node !=null?rx.node:ry.node, false); - } -} - -``` - -##### **BST Sequences**: A binary search tree was created by traversing through an array from left to right and inserting each element. Given a binary search tree with distinct elements, print all possible arrays that could have led to this tree. - -- Leetcode 449. Serialize and Deserialize BST -- Leetcode 297. Serialize and Deserialize Binary Tree - - - - - -##### **Check Subtree**: Tl and T2 are two very large binary trees, with Tl much bigger than T2. Create an algorithm to determine if T2 is a subtree of Tl. A tree T2 is a subtree of Tl if there exists a node n in Tl such that the subtree of n is identical to T2. That is, if you cut off the tree at node n, the two trees would be identical. - -- Leetcode 700. Search in a Binary Search Tree -- Leetcode 572. Subtree of Another Tree - - -##### **Random Node**: You are implementing a binary tree class from scratch which, in addition to insert, find, and delete, has a method getRandomNode() which returns a random node from the tree. All nodes should be equally likely to be chosen. Design and implement an algorithm for getRandomNode, and explain how you would implement the rest of the methods. - -- 用array存取每個樹中每個節點,return 隨機元素 O(N) space O(N) time -- 用array存取每個樹中每個節點,return 隨機元素並刪除該元素 O(N) space O(N) time -- 可以用Inoreder traverse 標註樹中每個節點1...N,並隨機生成一個數字介於1到N之間,用binary search tree search t ofid the index O(N) time -- [Not working] - - 1/3 odds traverse the current root - - 1/3 odds traverse left - - 1/3 odds traverse right - - 或是隨機決定深度 - -- 假設當初在建樹時有紀錄size,知道節點個數,針對上面方法做改善,O(logN) time - -```java -class TreeNode{ - private int data; - public TreeNode left; - public TreeNode right; - private int size = 0; - public TreeNode(int d){ - data = d; - size = 1; - } - public TreeNode getRandomNote(){ - int leftSize = left ==null?0:left.size(); - Random random = new Random(); - int index = random.nextInt(size); - if(indexdata){ - return right != null?right.find(d):null; - } - return null; - } -} -``` - - - -O(logN) - -```java - -class Tree{ - TreeNode root= nullptr; - public int size() {return root ==null ?0 : root.size();} - public TreeNode getRandomNode(){ - if(root==null) return null; - - Random random = new Random(); - int i = random.nextInt(size()); - return root.getIthNode(i); - } - public void insertInOrder(int value){ - if(root=null){ - root = new TreeNode(value); - } - else{ - root.insertInOrder(value); - } - } -} -class TreeNode{ - - public TreeNode getIthNode(int i){ - int leftSize = left ==null ?0:left.size(); - if(idata){ - return right != null?right.find(d):null; - } - return null; - - } -} -``` -##### **Paths with Sum**: You are given a binary tree in which each node contains an integer value (which might be positive or negative). Design an algorithm to count the number of paths that sum to a given value. The path does not need to start or end at the root or a leaf, but it must go downwards (traveling only from parent nodes to child nodes). - - -- Leetcode 112. Path Sum -- Leetcode 113. Path Sum II -- Leetcode 437. Path Sum III -- Leetcode 666. Path Sum IV - - - -437 Path Sum III -Brute force O(N log N)in a balanced tree -```cpp -int countPathsWithSumFromNode(TreeNode *node, int targetSum , int currentSum ){ - if(!node) return 0; - - currentSum += node->val; - int totalPaths = 0; - if (currentSum == targetSum) { // Found a path from the root - totalPaths++; - } - - totalPaths += countPathsWithSumFromNode(node->left, targetSum, currentSum); - totalPaths += countPathsWithSumFromNode(node->right, targetSum, currentSum); - return totalPaths; - - - } - int countPathsWithSum(TreeNode* root, int targetSum){ - if(!root) return 0; - - /* Count paths with sum starting from the root. */ - int pathsFromRoot = countPathsWithSumFromNode(root, targetSum, 0); - - /* Try the nodes on the left and right. */ - int pathsOnLeft = countPathsWithSum(root->left, targetSum); - int pathsOnRight = countPathsWithSum(root->right, targetSum); - return pathsFromRoot + pathsOnLeft + pathsOnRight; - } - - int pathSum(TreeNode* root, int targetSum) { - return countPathsWithSum(root, targetSum); - } - -``` - -O(N) time -O(logN)in a balanced tree - -```java -int countPathWithSum(TreeNode root, int targetSum){ - return countPathWitheSum(root, targetSum, 0, new HashMap()); -} -int countPathWitheSum(TreeNode root, int targetSum, int runningSum, HashMap pathCount){ - if(node==null) return 0; // Base case - /* Count paths with sum ending at the the current node */ - runningSum += node.data; - int sum = runningSum -targetSum; - int totalPaths = pathCount.getOrDefault(sum , 0); - - /* If runningSum eaquls targetSum , then one additionl path starts at root. Add in this path */ - if(runningSum == targetSum) totalPaths++; - - /* Increment pathCount, recurse, then decrement pathCount. */ - incrementHashTable(pathCount, runningSum, 1); - totalPaths+= countPathWitheSum(root.left, targetSum, runningSum, pathCount); - totalPaths+= countPathWitheSum(root.right, targetSum, runningSum, pathCount); - incrementHashTable(pathCount, runningSum, -1); - return totalPaths; -} - -void incrementHashTable(HashMap hashTable, int key, int delta){ - int newCount = hashTable.getOrDefault(key,0) + delta; - if(newCount==0) hashTable.reome(key); - else hashTable.put(key, newCount); -} - -``` - -## Bit Manipulation -x^ 000000 = x -x^ 111111 = ~x -x^ x = 0 -x | x = x - -##### **Insertion**: You are given two 32-bit numbers, N and M, and two bit positions, i and j. Write a method to insert M into N such that M starts at bit j and ends at bit i. You can assume that the bits j through i have enough space to fit all of M. That is, if M = 10011, you can assume that there are at least 5 bits between j and i. You would not, for example, have j = 3 and i = 2, because M could not fully fit between bit 3 and bit 2. - - -```java - -int updateBits(int n, int m, int i , int ,j){ - // EXAMPLE - // input: N = 10000000000, M = 10011 , i=2 j= 6 - // output: N = 10001001100 - // - int allOnes = ~0; // will equal sequence of all 1s. - - // 1s before position j, then 0s. left = 11110000000 - int left = allOnes << (j+1); - - // 1's after position i . right = 00000000100 - 1 = 00000000011 - int right = ((1<=1 || num<=0) return "ERROR"; - - StringBuilder binary = new StringBuilder(); - binary.append("."); - while(num>0){ - if(binary.length() >=32){ - return "ERROR"; - } - - double r = num*2; - if(r>=1){ - binary.append(1); - num = r-1; - } - else{ - binary.append(0); - num = r; - } - } - return binary.toString(); -} - -``` - - - -```java - -String printBinary(double num){ - if(num>=1 || num<=0) return "ERROR"; - - StringBuilder binary = new StringBuilder(); - double frac = 0.5; - binary.append("."); - while(num>0){ - if(binary.length() > 32){ - return "ERROR"; - } - - if(num>=frac){ - binary.append(1); - num -= frac; - } - else{ - binary.append(0) - } - frac /=2; - } - return binary.toString(); -} -``` - - -##### **Flip Bit to Win**: You have an integer and you can flip exactly one bit from a 0 to a 1. Write code to find the length of the longest sequence of ls you could create. - -- [Length of the Longest Consecutive 1s in Binary Representation](https://www.geeksforgeeks.org/length-longest-consecutive-1s-binary-representation/?ref=lbp) - -- [Find longest sequence of 1’s in binary representation with one flip](https://www.geeksforgeeks.org/find-longest-sequence-1s-binary-representation-one-flip/) - -```java -// brute force -// EXAMPLE -// input : 1175 (or: 11011101111) seq = [0,4,1,3,1,2,21] reading bfrom right to left -// output 8 -// O(b) time and O(b) space , where b in the length of the sequence. -int longestSequence(int n){ - if(n==-1) return Integer.BYTES*8; - ArrayList sequences = getAlternatingSequeces(n); - return findLongestSequence(sequences); -} -/* Return a list of the sizes of the sequences. The sequence starts off with the - number of 0s (which might be 0) and then alternates with the counts of each value - */ -ArrayList getAlternatingSequeces(int n){ - ArrayList sequences = new ArrayList(); - - int searchingFor = 0; - int counter = 0; - - for(int i=0;i>>=1; - } - sequences.add(counter); - return sequences; //seq = [0,4,1,3,1,2,21] -} -/* Given the lengths of alternating sequences of 0s and ls, find the longest one - we can build. */ -int findLongestSequence(ArrayList seq){ - int maxSeq = 1; - for(int i=0;i=0 ? seq.get(i-1):0; - int onesSeqLeft = i+1 1){ // just add a zero to either side - thisSeq = 1+ Math.max(onesSeqRight, onesSeqLeft); - } - else if(zerosSeq==0){ // No zero, but take either size - thisSeq = Math.max(onesSeqRight, onesSeqLeft); - } - maxSeq = Math.max(thisSeq, maxSeq); - } - return maxSeq; -} -``` - - - -```java - -// O(b) time but O(1) space -// When we see a zero, update previous Length: -// If the next bit is a 1, previous Length should be set to current Length. -// If the next bit is a 0, then we can't merge these sequences together. So, set previous Length to 0. - -int flipBit(int a){ - /* If all 1s , this is already the longest sequence */ - if(~a==0) return Integer.BYTES*8; - - int currentLength = 0; - int previousLength = 0; - int maxLength = 1 ; - - while(a!=0){ - if((a&1) == 1){ - currentLength++; - } - else if((a&1)==0){ - previousLength = (a&2)==0?0:currentLength; - currentLength = 0; - } - - maxLength = Math.max(previousLength + currentLength +1 , maxLength); - a >>>=1; - } - return maxLength; -} -``` - -##### **Next Number**: Given a positive integer, print the next smallest and the next largest number that have the same number of 1 bits in their binary representation. - -```java - -// Bit Manipulation for Get Next Number -// EXAMPLE 13948 = 1101101111100 -// step 1 Flip rightmost non-trailing zero => 11011011111100 -// step 2 Clear bits to the right of p from befor, c0 = 2, c1 = 5, p=7 => 11011010000000 -// a = 1< 11011010001111 -// a = 1<< (c1-1); -// b= a-1; -// n = n| b; -// equal to -// n |= (1<<(c1-1)) -1; - -int getNext(int n){ - /* compute c0 and c1 */ - int c = n; - int c0 = 0; - int c1 = 0; - - while( ((c&1)==0) && (c!=0) ){ - c0++; - c >>= 1; - } - while( (c&1) ==1){ - c1++; - c >>= 1 ; - } - - - /* Error: if n == 11..1100...00, then there is no bigger number with the same number of 1s*/ - if(c0+c1 ==31 || c0+c1 ==0){ - return -1; - } - int p = c0+c1; //position of rightmost non-trailing zeros - - n |= (1<>=1; - } - - if(temp==0)return -1; - - while( ((temp&1)==0 ) && (temp!=0)){ - c0++; - temp>>=1; - } - - - - - int p = c0+c1; - n &= ((~0) << (p+1)); // clears from bits p onwards - - int mask = (1<<(c1+1))-1; //Sequence of (c1+1) ones - - n|= mask <<(c0-1); - - return n -} - -// Arithmetic Approach for Get Next Number -// c0 is the number of trailing zeros, c1 is the size of the one block immediately followind, and p=c0+c1, -// we can word our solution from eariler as follows -// step 1 set the Pth bit to 1 -// step 2 set all bits following p to 0 -// step 3 set bits 0 through c1-2 to 1. This will be c1-1 total bits -// n+= 2^c0 -1 -// -int getNextArith(int n){ - int c = n; - int c0 = 0; - int c1 = 0; - - while( ((c&1)==0) && (c!=0) ){ - c0++; - c >>= 1; - } - while( (c&1) ==1){ - c1++; - c >>= 1 ; - } - - return n + (1 << c0) + (1 << (c1 - 1)) - 1; -} - - -// Arithmetic Approach for Get Previous Number -// c1 is the number of trailing ones , c0 is the size of the zero block immediately following, -// and p = c0+c1 -// step 1 set the Pth bit to 1 -// step 2 set all bits following p to 0 -// step 3 set bits 0 through c1-2 to 1. This will be c1-1 total bits - - -int getPrevArith(int n){ - int temp = n; - int c0 = 0; // the size of block of zeros immediately to the left of the trailing ones - int c1 = 0; // c1 is the number of trailing ones - while( ( temp&1)==1){ - c1++; - temp>>=1; - } - - if(temp==0)return -1; - - while( ((temp&1)==0 ) && (temp!=0)){ - c0++; - temp>>=1; - } - - return n - (1 << c1) - (1 << (c0 - 1)) + 1; - - -} -``` -##### **Debugger**: Explain what the following code does: ((n & (n-1)) == 0). - - -- A&B==0 -- A and B never have a 1 bit in the same place. -- 當你減一,都是看在最低有效位,如果是一變成零。如果是零,你必須借位更大一位的bit,當你遞增地向高位,遞增同時遇到零變成1,直到遇到1,並將他變為0 - - - -##### **Conversion**: Write a function to determine the number of bits you would need to flip to convert integer A to integer B. - - -- XOR - - -```java -int bitSwapRequired(int a, int b){ - int count = 0; - for(int c = a^b ; c!=0 ; c =c >>1){ - count += (c&1); - } - return count; -} - - -// c = c & (c - 1) will clear the least significant bit in c - - -int bitSwapRequired(int a, int b){ - int count = 0; - for(int c = a^b ; c!=0 ; c = c &(c-1)){ - count ++; - } - return count; -} - - -``` - -##### **Pairwise Swap**: Write a program to swap odd and even bits in an integer with as few instructions as possible (e.g., bit 0 and bit 1 are swapped, bit 2 and bit 3 are swapped, and so on). - -we take a number n and move the odd bits over by 1 -mask all odd bits with 10101010 in binary(which is 0xAA), then shift them right by 1 to put them in the even spots. -fro the even bits , we do an equivalent operation. -```java -0xa = 1010 , 0x5 = 0101 - -int swapOddEvenBits(int x){ - return ( ((x& 0xaaaaaaaa)>>>1 ) | ((x& 0x55555555)<<1) ); -} -``` - -##### **Draw Line**: A monochrome screen is stored as a single array of bytes, allowing eight consecutive pixels to be stored in one byte. The screen has width w, where w is divisible by 8 (that is, no byte will be split across rows). The height of the screen, of course, can be derived from the length of the array and the width. Implement a function that draws a horizontal line from (xl, y) to ( x2, y) - - -A naive solution to the problem is straightforward: iterate in a for loop from xl to x2, setting each pixel along the way - -A better solution is to recognize that if xl and x2 are far away from each other, several full bytes will be contained between them. -These full bytes can be set one at a time by doing screen[byte_pos] 0xFF. -he residual start and end of the line can be set using masks. - -```java -void drawLine(byte[] screen , int width, int x1, int x2, int y){ - int start_offset = x1%8; - int first_full_byte = x1 / 8; - - if(start_offset !=0){ - first_full_byte++; - } - int end_offset = x2%8; - int last_full_byte = x2/8; - if(end_offsetet!=7){ - last_full_byte--; - } - - // set full bytes - for(int b = first_full_byte ; b<=last_full_byte; ++b){ - screen[(width/8)*y + b] = (byte) 0xFF; - } - - // create masks for start and end of line - byte start_mask = (byte)(0xFF >> start_offset); - byte end_mask = (byte) ~(0xFF >> (end_offset + 1)); - - // set start and end of lines - if( (x1/8) == (x1/8)){ // xl and x2 are in the same byte - byte mask= (byte) (start_mask & end_mask); - screen[(width/ 8) * y + (xl / 8)] I= mask; - } - else{ - if (start_offset != 0) { - int byte_number =(width/ 8) * y + first_full_byte - 1; - screen[byte_number] I= start_mask; - } - if(end_offset !=7){ - int byte_number =(width/ 8) * y + last_full_byte + 1; - screen[byte_number] I= end_mask; - } - } -} -``` - - -## Math and Logic Puzzles - -##### **The Heavy Pill**: You have 20 bottles of pills. 19 bottles have 1.0 gram pills, but one has pills of weight 1.1 grams. Given a scale that provides an exact measurement, how would you find the heavy bottle? You can only use the scale once. - -we must weigh multiple pills at the same time. -用平均法去排除 - - -- **Basketball**: You have a basketball hoop and someone says that you can play one of two games. -Game 1: You get one shot to make the hoop. -Game 2: You get three shots and you have to make two of three shots. -If p is the probability of making a particular shot, for which values of p should you pick one game or the other? -3. **Dominos**: There is an 8x8 chessboard in which two diagonally opposite corners have been cut off. You are given 31 dominos, and a single domino can cover exactly two squares. Can you use the 31 dominos to cover the entire board? Prove your answer (by providing an example or showing why it's impossible). -4. **Ants on a Triangle**: There are three ants on different vertices of a triangle. What is the probability of collision (between any two or all of them) if they start walking on the sides of the triangle? Assume that each ant randomly picks a direction, with either direction being equally likely to be chosen, and that they walk at the same speed. -Similarly, find the probability of collision with n ants on an n-vertex polygon -5. **Jugs of Water**: You have a five-quart jug, a three-quart jug, and an unlimited supply of water (but no measuring cups). How would you come up with exactly four quarts of water? Note that the jugs areoddlyshaped,suchthatfillingupexactly"half"ofthejugwouldbeimpossible -6. **Blue-Eyed Island**: A bunch of people are living on an island, when a visitor comes with a strange order: all blue-eyed people must leave the island as soon as possible. There will be a flight out at 8:00 pm every evening. Each person can see everyone else's eye color, but they do not know their own (nor is anyone allowed to tell them). Additionally, they do not know how many people have blue eyes, although they do know that at least one person does. How many days will it take the blue-eyed people to leave? -7. **The Apocalypse**: In the new post-apocalyptic world, the world queen is desperately concerned about the birth rate. Therefore, she decrees that all families should ensure that they have one girl or else they face massive fines. If all families abide by this policy-that is, they have continue to have children until they have one girl, at which point they immediately stop-what will the gender ratio of the new generation be? (Assume that the odds of someone having a boy or a girl on any given pregnancy is equal.) Solve this out logically and then write a computer simulation of it. -8. **The Egg Drop Problem**: There is a building of 100 floors. If an egg drops from the Nth floor or above, it will break. If it's dropped from any floor below, it will not break. You're given two eggs. Find N, while minimizing the number of drops for the worst case. -9. **100 Lockers**: There are 100 closed lockers in a hallway. A man begins by opening all 100 lockers. Next, he closes every second locker. Then, on his third pass, he toggles every third locker (closes it if it is open or opens it if it is closed). This process continues for 100 passes, such that on each pass i, the man toggles every ith locker. After his 100th pass in the hallway, in which he toggles only locker #100, how many lockers are open? -10. **Poison**: You have 1000 bottles of soda, and exactly one is poisoned. You have 10 test strips which can be used to detect poison. A single drop of poison will turn the test strip positive permanently. You can put any number of drops on a test strip at once and you can reuse a test strip as many times as you'd like (as long as the results are negative). However, you can only run tests once per day and it takes seven days to return a result. How would you figure out the poisoned bottle in as few days as possible? - - - -## Recursion and Dynamic Programming -* Recursive algorithms can be very space inefficient. -* All recursive algorithms can be implemented iteratively, although sometimes the code to do so is much more complex. - - -##### **Triple Step**: A child is running up a staircase with n steps and can hop either 1 step, 2 steps, or 3 steps at a time. Implement a method to count how many possible ways the child can run up the stairs. - - -- Leetcode 70. Climbing Stairs -- Leetcode 509. Fibonacci Number - - - -##### **Robot in a Grid**: Imagine a robot sitting on the upper left corner of grid with r rows and c columns. The robot can only move in two directions, right and down, but certain cells are "off limits" such that the robot cannot step on them. Design an algorithm to find a path for the robot from the top left to the bottom right. - - -- Leetcode 62. Unique Paths -- Leetcode 63. Unique Paths II -- Leetcode 64. Minimum Path Sum - - - - -##### **Magic Index**: A magic index in an array A[ 0••• n -1] is defined to be an index such that A[ i] = i. Given a sorted array of distinct integers, write a method to find a magic index, if one exists, in array A. - -brute force -```java - -// brute force -int magicSlow(int []array){ - for(int i=0;imid ) end = mid-1; - else start = mid+1; - } -} - -// assume elements are not distinct -int magicFast(int []array){ - return magicFast(array, 0 ,array.length-1); -} -int magicFast(int []array , int start, int end){ - if(end0) return left; - - /* Search Right */ - int rightindex = Math.max(midindex + 1, midValue); - int right = magicFast(array, rightlndex, end); - return right; - -} -``` - -##### **Power Set**: Write a method to return all subsets of a set. - -- Leetcode 78. Subsets -- Leetcode 90. Subsets II - - - - - -##### **Recursive Multiply**: Write a recursive function to multiply two positive integers without using the *operator.You can use addition, subtraction, and bit shifting, but you should minimize the number of those operations. - - -```java -int minProduct(int a, int b){ - int bigger = a>1 - int side1 = minProduct(s, bigger); - int side2 = side1; - if(smaller %2==1) side2 = minProductHelper(smaller-s , bigger); - return side1+side2; -} -``` - -memo - - -```java - -int minProduct(int a, int b, int []memo){ - int bigger = a0) return memo[smaller]; - - int s = smaller >>1 - int side1 = minProduct(s, bigger, memo); - int side2 = side1; - if(smaller %2==1) side2 = minProductHelper(smaller-s , bigger, memo); - memo[smaller] = side1 + side2 ; - - return memo[smaller]; -} -``` - - -O(log s) time, s is the smaller of two numbers. -```java - -int minProduct(int a, int b){ - int bigger = a>1 - int halfProd = minProduct(s, bigger); - int side2 = side1; - if(smaller %2==0) return halfProd + halfProd;; - else retrun halfProd + halfProd + bigger; - - -} -``` - -##### **Towers of Hanoi**: In the classic problem of the Towers of Hanoi, you have 3 towers and N disks of different sizes which can slide onto any tower. The puzzle starts with disks sorted in ascending order of size from top to bottom (i.e., each disk sits on top of an even larger one).You have the following constraints: -(1) Only one disk can be moved at a time. -(2) A disk is slid off the top of one tower onto another tower. -(3) A disk cannot be placed on top of a smaller disk. -Write a program to move the disks from the first tower to the last using stacks. - - -- [Towers of Hanoi](https://www.geeksforgeeks.org/c-program-for-tower-of-hanoi/) - - -```java - -void main(String [] args){ - int n = 3; - Tower[] towers = new Tower[n]; - for(int i = 0;i<3;++i){ - towers[i] = new Tower(i); - } - - for(int i=n-1;i>=0;i--){ - towers[0].add(i); - } - towers[0].moveDisk(n, towers[2], towers[1]); -} - -class Tower{ - private Stack disks; - private int index;public Tower(int i ){ - disks = new Stack(); - index = i; - } - public int index(){ - return index; - } - - public void add(int d){ - if(!disks.isEmpty() && disks.peek()<=d){ - System.out.println("Error placing disk" + d); - } - else{ - disks.push(d); - } - } - public void moveTopTo(Tower t){ - int top = disks.top(); - t.add(top); - } - public void moveDisks(int n, Tower destination, Tower buffer){ - if(n>0){ - moveDisks(n-1, buffer, destination); - moveTopTo(destination); - buffer.moveDisks(n-1 , destination, this); - } - } -} - -``` - - -##### **Permutations without Dups**: Write a method to compute all permutations of a string of unique characters. - -Approach 1: Building from permutations of first n-1 characters. - - -```java - -Arraylist getPerms(String str) { - if (str == null) return null; - Arraylist permutations new ArrayList(); - if (str.length() == 0) {//base case - permutations. add('"'); - return permutations; - } - - char first= str.charAt(0); // get the first char - String remainder= str.substring(l); // remove the first char - Arraylist words= getPerms(remainder); - for(String word :words){ - for(int j =0;j getPerms(String str) { - Arraylist result = new Arraylist(); - getPerms("", str, result); - return result; - -} - - -void getPerms(String prefix, String remainder, Arraylist result) { - if (remainder.length()== 0) result.add(prefix); - - int len = remainder.length(); - for (int i= 0; i < len; i++) { - String before = remainder.substring(0, i); - String after = remainder.substring(i+1, len); - char c =remainder.charAt(i); - getPerms(prefix+c, before+after, result); - } -} -``` - -- Leetcode 46. Permutations - - -##### **Permutations with Dups**: Write a method to compute all permutations of a string whose charac­ ters are not necessarily unique. The list of permutations should not have duplicates. - -- Leetcode 47. Permutations II -用vector 或是 hash 去判斷是否拜訪過 - - -```java -Arraylist printPerms(String s) { - Arraylist result; - HashMap map = buidFreqTable(s); - printPerms(map, "", s.length(), result); - - return result; -} - -HashMap buidFreqTable{ - HashMap map= new HashMap(); - for (char c : s.toCharArray()) { - if(!map.containsKey(c)){ - map.put(c,0); - } - map.put(c, map.get(c) + 1); - } - return map; -} - -void printPerms(HashMap map, String prefix, int remaining,Arraylist result){ - /* Base case. Permutation has been completed. */ - if (remaining== 0) {{ - result.add(prefix); - return; - } - - /* Try remaining letters for next char, and generate remaining permutations. */ - for (Character c : map.keySet()) { - int count = map.get(c).toInt(); - if(count>0){ - map.put(c, count-1); - printPerms(map, prefix+c, remaining-1, result) - map.put(c, count); - } - } -} -``` - - - -##### **Parens**: Implement an algorithm to print all valid (e.g., properly opened and closed) combinations of n pairs of parentheses. - -- Leetcode 20. Valid Parentheses -- Leetcode 22. Generate Parentheses - - - -##### **Paint Fill**: Implement the "paint fill" function that one might see on many image editing programs. That is, given a screen (represented by a two-dimensional array of colors), a point, and a new color, fill in the surrounding area until the color changes from the original color. - - -- Leetcode 733. Flood Fill - - -##### **Coins**: Given an infinite number of quarters (25 cents), dimes (10 cents), nickels (5 cents), and pennies (1 cent), write code to calculate the number of ways of representing n cents. - -- Leetcode 322. Coin Change - - - -```java -int makeChanges(int amount , int []denoms, int index){ - if(index > denoms.length-1) return 1; //last denom - - int denomAmount =denoms[index]; - int ways = 0 ; - - for(int i=0;i* denomAmount <= amount;++i){ - int amountRemaining = amount - i*denomAmount; - ways += makeChanges(amountRemaining, denoms, index+1); - } - return ways; -} - -int makeChanges(int n){ - int[] denoms = {25,10,5,1}; - return makeChanges(n, denoms, 0); -} - - -// memo - -int makeChanges(int amount , int []denoms, int index, int[][] map){ - if(map[amount][index] >0) return map[amount][index]; - - if(index > denoms.length-1) return 1; //last denom - - int denomAmount =denoms[index]; - int ways = 0 ; - - for(int i=0;i* denomAmount <= amount;++i){ - int amountRemaining = amount - i*denomAmount; - ways += makeChanges(amountRemaining, denoms, index+1); - } - map[amount][index] = ways; - return ways; -} - -int makeChanges(int n){ - int[] denoms = {25,10,5,1}; - int[][] map = new int[n+1][denoms.length]; - return makeChanges(n, denoms, 0); -} - - -``` - - - - -##### **Eight Queens**: Write an algorithm to print all ways of arranging eight queens on an 8x8 chess board so that none of them share the same row, column, or diagonal. In this case, "diagonal" means all diagonals, not just the two that bisect the board. - -- Leetcode 51. N-Queens -- Leetcode 52. N-Queens II - -```java - -int GRID_SIZE = 8 ; - -void placeQueens(int row, Integer[] columns, ArrayList results){ - if(row == GRID_SIZE){ - results.add(columns.clone()); - } - else{ - for(int col = 0; col last) return -1; - - int mid = (last + first )/2; - - if(strings[mid].isEmpty()){ - int left = mid -1; - int right = mid +1; - - while(true){ - if(left < first && right > last){ - return -1; - } - else if(right <=last && !strings[right].isEmpty()){ - mid = right; - break; - } - else if(left >=first && !strings[left].isEmpty()){ - mid = left; - break; - } - right++; - left--; - } - } - if(str.equals(strings[mid])){ //found it - return mid; - } - else if(strings[mid].compareTo(str)<0){ //search right - return search(strings, str, mid+1, last); - } - else{ //search left - return search(strings, str, first, mid-1); - } - -} - -int search(String[] strings, String str){ - if(strings == null || str == null || str=="") return -1; - - return search(strings, str,0, str.length-1); -}``` - - - - - - -##### **Sort Big File**: Imagine you have a 20 GB file with one string per line. Explain how you would sort the file. - - -- it suggests that they don't want you to bring all the data into memory. -- We'll divide the file into chunks, which are x megabytes each, where x is the amount of memory we have available. Each chunk is sorted separately and then saved back to the file system. -- Once all the chunks are sorted, we merge the chunks, one by one. At the end, we have a fully sorted file. -- This algorithm is known as external sort. - - -##### **Missing Int**: Given an input file with four billion non-negative integers, provide an algorithm to generate an integer that is not contained in the file. Assume you have 1 GB of memo ry available for this task. - -```java -FOLLOW UP -What if you have only 10 MB of memory? Assume that all the values are distinct and we now have no more than one billion non-negative integers. - - - -long numberOflnts = ((long) Integer.MAX_VALUE) + 1; -byte[] bitfield new byte [(int) (numberOfints / 8)]; -String filename = ................ -void findOpenNumber() throws FileNotFoundException { - Scanner in = new Scanner(new FileReader(filename)); - while (in.hasNextint()) { - int n = in.nextlnt (); - /* Finds the corresponding number in the bitfield by using the OR operator to - * set the nth bit of a byte (e.g., 10 would correspond to the 2nd bit of - * index 2 in the byte array). */ - bitfield[n/8] I=1«(n%8); - } - for (int i= 0; i < bitfield.length; i++) { - for (int j= 0; j < 8; j++) { - /* Retrieves the individual bits of each byte. When 0 bit is found, print - * the corresponding value. */ - if ((bitfield[i] & (1 << j)) == 0) { - System.out.println (i * 8 + j); - return ; - } - } - } -} - - -// Follow Up: What if we have only 10 MB memory? -int findOpenNumber(String filename) throws FileNotFoundException { - int rangeSize = (1 << 20); // 2A20 bits (2A17 bytes) - /* Get count of number of values within each block. */ - int[] blocks = getCountPerBlock(filename, rangeSize); - - /* Find a block with a missing value. */ - int blocklndex findBlockWithMissing(blocks, rangeSize); - if (blocklndex < 0) return -1; - - /* Create bit vector for items within this range. */ - byte[] bitVector = getBitVectorForRange(filename, blockindex, rangeSize); - - /* Find a zero in the bit vector */ - int offset findZero(bitVector); - if (offset <0) return -1; - - /* Compute missing value. */ - return blockindex * rangeSize + offset; -} - - -/* Get count of items within each range. */ -int[] getCountPerBlock(String filename, int rangeSize) throws FileNotFoundException { - - int arraySize = Integer.MAX_VALUE / rangeSize + 1; - int[] blocks = new int[arraySize]; - Scanner in = new Scanner (new FileReader(filename)); - while (in.hasNextint()) { - int value = in.nextint(); - blocks[value / rangeSize]++; - } - in.close(); - return blocks; -} - -/* Find a block whose count is low. */ -int findBlockWithMissing(int[] blocks, int rangeSize) { - for (int i= 0; i < blocks.length; i++) { - if (blocks[i] >5) +1 ]; //divid by 32 - } - - boolean get(int pos){ - int wordNumber = (pos >> 5); // divide by 32 - int bitNumber = (pos & 0x1F); // mod 32 - return (bitset[wordNumber] & (1 << bitNumber)) != 0; - } - - void set(int pos){ - int wordNumber = (pos >> 5); // divide by 32 - int bitNumber = (pos & 0x1F); // mod 32 - bitset[wordNumber] I= 1 << bitNumber; - } - -``` - - -##### **Sorted Matrix Search**: Given an M x N matrix in which each row and each column is sorted in ascending order, write a method to find an element. - - -binary search or 雙指標並從左下或右上開始搜尋 -- Leetcode 74. Search a 2D Matrix -- Leetcode 240. Search a 2D Matrix II - - -##### **Rank from Stream**:Imagine you are reading in a stream of integers. Periodically, you wish to be able to look up the rank of a numberx (the number of values less than or equal tox). lmplement the data structures and algorithms to support these operations. That is, implement the method track ( int x), which is called when each number is generated, and the method getRankOfNumber(int x), which returns the number of values less than or equal tox (not includingx itself). - -- Leetcode 496. Next Greater Element I -- Leetcode 503. Next Greater Element II -- Leetcode 1019. Next Greater Node In Linked List -- Leetcode 739. Daily Temperatures - - - - -##### **Peaks and Valleys**: In an array of integers, a"peak" is an element which is greater than or equal to the adjacent integers and a "valley" is an element which is less than or equal to the adjacent inte­ gers. For example, in the array {5, 8, 6, 2, 3, 4, 6}, {8, 6} are peaks and {5, 2} are valleys. Given an array of integers, sort the array into an alternating sequence of peaks and valleys. - - - - - - -## 別人的解答 - -- [解答](https://www.cnblogs.com/grandyang/p/5162994.html) \ No newline at end of file diff --git a/Cracking-the-coding-interview-part2.md b/Cracking-the-coding-interview-part2.md deleted file mode 100644 index 039ae48..0000000 --- a/Cracking-the-coding-interview-part2.md +++ /dev/null @@ -1,535 +0,0 @@ -# Cracking the coding interview part 2 - - -###### tags: `interview` `algorithm` - - -[toc] - -## C and C++ -must know -- Classes and Inheritance -- Constructors and Destructors -- Virtual Functions -- Virtual Destructor -- Default Values -- Operator Overloading -- Pointers and References -- Templates - - -##### **Last K Lines**: Write a method to print the last K lines of an input file using C++. - -```cpp -void printLast10Lines(char * fileName){ - const int k = 10; - ifstream file(fileName); - string L[K]; - int size = 0; - - while(file.peek()!= EOF){ - getline(file, L[size % K]); - size++; - } - int start = size> K ? (size%k) : 0; - int count = min(K, size); - - for(int i = 0;i){ - cout<circumference(); // "Circumference of Base Class" - Shape *y = new Triangle(); - y->circumference(); // "Circumference of Triangle Class" - - return 0; -} -``` -##### Shallow vs. Deep Copy: What is the difference between deep copy and shallow copy? Explain how you would use each. - -淺拷貝將所有成員值從一個對象複製到另一個對象。 深拷貝完成所有這些,並且還深拷貝任何指針對象。 - -```cpp -struct Test{ - char * ptr; -}; - -void shallow_copy(Test &src, Test &dest){ - dest.ptr = src.ptr; -} -void deep_copy(Test &src, Test & dest){ - dest.ptr = (char*)malloc(strlen(src.ptr)+1) - strcpy(dest.ptr, src.ptr); -} - -``` - -淺拷貝有時會引起許多運行錯誤,尤其是在創建和刪除對象時後。淺拷貝不常使用,深拷貝應該是大多情況下使用。 -##### **Volatile**: What is the significance of the keyword "volatile" in C? - -關鍵字 volatile 通知編譯器它所應用的變數的值可以從外部更改,如作業系統、硬體或另一個執行緒。 由於該值可能會意外更改,因此編譯器每次都會從記憶體中重新加載該值。 - -Volatile variables are not optimized, which can be very useful. Imagine this function: -```cpp -// 定義整數型變量 -int volatile x; -volatile int x; -// 定義指標變數 -volatile int *x; -int volatile *x; -``` -```cpp -int opt = 1; -void Fn(void) { - start: - if(opt==1) goto start; - else break; -} -// 乍看之下,上面程式是死循環,編譯器會自動優化成 -// At first glance, our code appears to loop infinitely. The compiler may try to optimize it to: -void Fn(void) { - start: - int opt = 1; - if(true) - goto start; -} -// 的確是死循環,但外部操作可以給變量opt 賦值0,這樣可以跳出迴圈。 -// This becomes an infinite loop. However, an external operation might write'O'to the location of variable opt, thus breaking the loop. -volatile int opt = 1; -void Fn(void) { - start: - if(opt==1) goto start; - else break; -// votlatile 變量可以再多執行緒程序中有全局變量且每個執行序可以改變共享值時非常方便,我們不想這些共享變數被優化 -``` -##### **Virtual Base Class**: Why does a destructor in base class need to be declared virtual? - -Destructors are used to clean up memory and resources. -```cpp -class Foo{ - public: - void f(); -}; -class Bar : public Foo{ - public: - void f(); -} -Foo *p = new Bar(); -p->f(); -// 調用p->f()會調用父類中的f(),這是因為f()不是虛函數。為了能調用子類中的f(),我們需要在父類定義其為虛函數。 -// Calling p->f() will result in a call to Foo: :f(). -``` -如果父類解構子不是虛函數,那子類也只會調用父類的解構子,而不會調用子類的解構子。這就是我們要定義解構子函數為虛函數的原因。 -If Foo's destructor were not virtual, then Foo's destructor would be called, even when p is really of type Bar. -This is why we declare destructors to be virtual; we want to ensure that the destructor for the most derived class is called. - -> 不要去繼承沒有 virtual destructor 的 class -> 在 class 裡寫到 virtual function 的時候就幫他加個 virtual destructor 以絕後患 -##### **Copy Node**: Write a method that takes a pointer to a Node structure as a parameter and returns a complete copy of the passed in data structure. The Node data structure contains two pointers to other Nodes. - -```cpp -typedef map NodeMap; - - -Node *copy_recursive(Node *cur, NodeMap & nodeMap){ - if(cur == nullptr){ - return nullptr; - } - - NodeMap::iterator i = nodeMap.find(cur); - if(i != nodeMap.end()){ // we've been here before, return the copy. - return i->second; - } - Node *node = new Node; - nodeMap[cur] = node; //map current before traversing links - node->ptr1 = copy_recursive(cur->ptr1, nodeMap); - node->ptr2 = copy_recursive(cur->ptr2, nodeMap); - return node; -} - - -Node *copy_recursive(Node *root){ - NodeMap nodeMap; //we will need an empty map - return copy_recursive(root, nodeMap); -} - - -``` - -##### **Smart Pointer**: Write a smart pointer class. A smart pointer is a data type, usually implemented with templates, that simulates a pointer while also providing automatic garbage collection. It automati­ cally counts the number of references to a SmartPointer object and frees the object of type T when the reference count hits zero. - -it provides safety via automatic memory management. It avoids issues like dangling pointers, memory leaks and allocation failures - -所謂智慧指標,就是除了普通指標的功能外,還能通過自動記憶體管理來提供安全性。避免一系列問題,如記憶體洩漏、分配失敗、迷途指標(指向非法物件的指標)。智慧指標必須維護一個飲用計數變數來統計給定對象的所有引用。實現過程主要有幾個部分: -1. 建構函數 -2. 拷貝建構函數(通過另一個值會指標物件建造) -3. 等號重載函數 -4. 解構函數 -5. 移除引用函數 - -```cpp -// pseudocode -template class SmartPointer{ - T* obj; - unsigned *ref_count; -} -SmartPointer(T *object){ -/* We want to set the value of T* obj, and set the reference counter to 1.*/ -} -SmartPointer(SmartPointer & sptr){ -/* This constructor creates a new smart pointer that points to an existing -* object. We will need to first set obj and ref_count to pointer to sptr's obj -* and ref_count. Then, because we created a new reference to obj, we need to -* increment ref_count.*/ -} -~SmartPointer(SmartPointer sptr){ -/* We are destroying a reference to the object. Decrement ref_count. If -14 * ref count is 0, then free the memory created by the integer and destroy the object */ -} - -onSetEquals(SmartPoint ptrl, SmartPoint ptr2) { - -} -``` - -```cpp -template class SmartPointer{ - public: - SmartPointer(T* ptr){ - ref = ptr; - ref_count = (unsigned*)malloc(sizeof(unsigned)); - *ref_count = 1; - } - SmartPointer(SmartPointer & sptr){ - ref = sptr.ref; - ref_count = sptr_ref_count(); - ++(*ref_count); - } - /* Override the equal operator, so that when you set one smart pointer equal to another the old smart pointer has its reference count decremented and the new smart pointer has its reference count incrememented. */ - - SmartPointer & operator=(SmartPointer & sptr) { - if(this == &sptr) return *thi; - - /* If already assigned to an object, remove one reference. */ - if (*ref_count > 0) { - remove(); - } - - ref = sptr.ref; - ref_count = sptr.ref_count; - ++(*ref_count); - return *this; - } - ~SmartPointer(){ - remove(); // Remove one reference to object. - } - - T getValue(){ - return *ref; - } - - protected: - void remove(){ - --(*ref_count); - if(*rer_count==0){ - delete ref; - free(ref_count); - ref = nullptr; - ref_count = nullptr; - } - } - - T *ref ; - unsigned *ref_count; -} -``` - - -##### **Malloc**: Write an aligned malloc and free function that supports allocating memory such that the memory address returned is divisible by a specific power of two. - -``` -EXAMPLE -align_malloc(1000, 128) will return a memory address that is a multiple of 128 and that points to memory of size 1000 bytes. -aligned_free() will free memory allocated by align_malloc. -``` - -```cpp -void* aligned_malloc(size_t required_bytes, size_t alignment) { - int offset = alignment - 1; - void* p= (void*) malloc(required_bytes + offset); - void* q = (void*) (((size_t)(p) + offset) & =(alignment - 1)); - return q; -} -void* aligned_malloc(size_t required_bytes, size t alignment) { - void* pl;// initial block - void* p2; // aligned block inside initial block - int offset= alignment - 1 + sizeof(void*); - if ((pl= (void*)malloc(required_bytes + offset))==nullptr){ - return nullptr; - } - p2 = (void*)(((size_t)(pl) + offset) & =(alignment - 1)); - ((void **)p2)[-1] = pl; - return p2; -} - -void aligned_free(void *p2){ - /* for consistency, we use the same names as aligned_malloc*/ - void *p1 = ((void**)p2)[-1]; - free(p1); - -} -``` - -##### **2D Alloc**: Write a function in C called my2DA1loc which allocates a two-dimensional array.Minimize the number of calls to malloc and make sure that the memory is accessible by the notation arr[i][j]. - - -```cpp -int** my2DA1loc(int rows, int cols) { - int** rowptr; - int i ; - rowptr = (int**) malloc(rows * sizeof(int*)); - for(i=0;i