diff --git a/README.md b/README.md deleted file mode 100644 index d81e6d2c..00000000 --- a/README.md +++ /dev/null @@ -1,24 +0,0 @@ -# 极客大学「算法训练营-第18期」作业提交仓库 - - - -## 仓库目录结构说明 - -1. `week01/` 代表第一周作业提交目录,以此类推。 -2. 请在对应周的目录下新建或修改自己的代码作业。 -2. 每周均有一个 `REDAME.md` 文档,你可以将自己当周的学习心得以及做题过程中的思考记录在该文档中。 - -## 作业提交规则 - -1. 先将本仓库 Fork 到自己 GitHub 账号下。 -2. 将 Fork 后的仓库 Clone 到本地,然后在本地仓库中对应周的目录下新建或修改自己的代码作业,当周的学习总结写在对应周的README.md文件里。 -3. 在本地仓库完成作业后,push 到自己的 GitHub 远程仓库。 -4. 最后将远程仓库中当周的作业链接,按格式贴到班级仓库对应学习周的issue下面。 -5. 提交issue请务必按照规定格式进行提交,否则作业统计工具将抓取不到你的作业提交记录。 - -详细的作业提交流程可以查阅:https://shimo.im/docs/m5rtM8K8rNsjw5jk/ - - -## 注意事项 - - 如果对 Git 和 GitHub 不太了解,请参考 [Git 官方文档](https://git-scm.com/book/zh/v2) 或者极客时间的[《玩转 Git 三剑客》](https://time.geekbang.org/course/intro/145)视频课程。 diff --git a/week01/1.two-sum.cs b/week01/1.two-sum.cs new file mode 100644 index 00000000..5aadf601 --- /dev/null +++ b/week01/1.two-sum.cs @@ -0,0 +1,29 @@ +/* + * @lc app=leetcode id=1 lang=csharp + * + * [1] Two Sum + */ + +// @lc code=start +using System.Collections.Generic; +public class Solution { + public int[] TwoSum(int[] nums, int target) { + //loop + //check complement num in Hash + //if yes return indexes + //else add nums[i] to hash + Dictionary dictionary=new Dictionary(); + for (int i = 0; i < nums.Length; i++) + { + int complement=target-nums[i]; + if (dictionary.ContainsKey(complement)) + { + return new int[]{i,dictionary[complement]}; + } + dictionary[nums[i]]=i; + } + return new int[2]{-1,-1}; + } +} +// @lc code=end + diff --git a/week01/189.rotate-array.cs b/week01/189.rotate-array.cs new file mode 100644 index 00000000..8a516654 --- /dev/null +++ b/week01/189.rotate-array.cs @@ -0,0 +1,38 @@ +/* + * @lc app=leetcode id=189 lang=csharp + * + * [189] Rotate Array + */ + +// @lc code=start +using System; + +public class Solution { + public void Rotate(int[] nums, int k) { + //k=k%nums.Length + //reverse n + //reverse k + //reverse remaining + k=k%nums.Length; + int n=nums.Length; + Reverse(nums,0,n-1); + Reverse(nums,0,k-1); + Reverse(nums,k,n-1); + + } + + private void Reverse(int[] nums, int start, int end) + { + while(startl1.val + //tail.next=l1 + //l1=l1.next + //tail=tail.next + //same thing for l2 + //combine remaining if either list is null + ListNode dummyHead=new ListNode(0); + ListNode tail=dummyHead; + while (l1!=null&&l2!=null) + { + if(l2.val>l1.val) + { + tail.next=l1; + l1=l1.next; + }else + { + tail.next=l2; + l2=l2.next; + } + tail=tail.next; + } + tail.next=l1==null?l2:l1; + return dummyHead.next; + } +} +// @lc code=end + diff --git a/week01/26.remove-duplicates-from-sorted-array.cs b/week01/26.remove-duplicates-from-sorted-array.cs new file mode 100644 index 00000000..0ffc9e51 --- /dev/null +++ b/week01/26.remove-duplicates-from-sorted-array.cs @@ -0,0 +1,31 @@ +/* + * @lc app=leetcode id=26 lang=csharp + * + * [26] Remove Duplicates from Sorted Array + */ + +// @lc code=start +public class Solution { + public int RemoveDuplicates(int[] nums) { + + //for + //if nums[i]!=nums[i-1] + //nums[count++]=nums[i] + if (nums.Length<2) + { + return nums.Length; + } + int count=1; + for (int i = 1; i < nums.Length; i++) + { + if (nums[i]!=nums[i-1]) + { + nums[count++]=nums[i]; + } + } + return count; + + } +} +// @lc code=end + diff --git a/week01/283.move-zeroes.cs b/week01/283.move-zeroes.cs new file mode 100644 index 00000000..8b707f3f --- /dev/null +++ b/week01/283.move-zeroes.cs @@ -0,0 +1,31 @@ +/* + * @lc app=leetcode id=283 lang=csharp + * + * [283] Move Zeroes + */ + +// @lc code=start +public class Solution { + public void MoveZeroes(int[] nums) { + //loop + //if nums[i]!=0 + //swap elements + + if (nums.Length<=1) + { + return; + } + int count=0; + for (int i = 0; i < nums.Length; i++) + { + if (nums[i]!=0) + { + int temp=nums[count]; + nums[count++]=nums[i]; + nums[i]=temp; + } + } + + } +} +// @lc code=end \ No newline at end of file diff --git a/week01/42.trapping-rain-water.cs b/week01/42.trapping-rain-water.cs new file mode 100644 index 00000000..db9b07f9 --- /dev/null +++ b/week01/42.trapping-rain-water.cs @@ -0,0 +1,48 @@ +/* + * @lc app=leetcode id=42 lang=csharp + * + * [42] Trapping Rain Water + */ + +// @lc code=start +using System; + +public class Solution { + public int Trap(int[] height) { + + if (height.Length<=2) + { + return 0; + } + + //loop n + //set Left[i] + + //loop n + // set right[i] + + //loop n + //water+=min(max left i, max right i) + int n=height.Length; + int[] left=new int[n]; + int[] right=new int[n]; + int water=0; + left[0]=height[0]; + for (int i = 1; i < n; i++) + { + left[i]=Math.Max(height[i],left[i-1]); + } + right[n-1]=height[n-1]; + for (int i = n-2; i >= 0; i--) + { + right[i]=Math.Max(height[i],right[i+1]); + } + for (int i = 0; i < n; i++) + { + water+=Math.Min(left[i],right[i])-height[i]; + } + return water; + } +} +// @lc code=end + diff --git a/week01/641.design-circular-deque.cs b/week01/641.design-circular-deque.cs new file mode 100644 index 00000000..9bd22346 --- /dev/null +++ b/week01/641.design-circular-deque.cs @@ -0,0 +1,124 @@ +/* + * @lc app=leetcode id=641 lang=csharp + * + * [641] Design Circular Deque + */ + +// @lc code=start +public class MyCircularDeque { + + /** Initialize your data structure here. Set the size of the deque to be k. */ + int front; + int rear; + int capacity; + int count; + int[] deque; + public MyCircularDeque(int k) { + front=0; + rear=-1; + capacity=k; + count=0; + deque=new int[k]; + } + + /** Adds an item at the front of Deque. Return true if the operation is successful. */ + public bool InsertFront(int value) { + if (!IsFull()) + { + count++; + front--; + if (front<0) + { + front=capacity-1; + } + deque[front]=value; + + //take note + if (count == 1) rear = front; + + return true; + } + return false; + } + + /** Adds an item at the rear of Deque. Return true if the operation is successful. */ + public bool InsertLast(int value) { + if (!IsFull()) + { + count++; + rear++; + if (rear>capacity-1) + { + rear=0; + } + deque[rear]=value; + return true; + } + return false; + } + + /** Deletes an item from the front of Deque. Return true if the operation is successful. */ + public bool DeleteFront() { + if (!IsEmpty()) + { + count--; + front++; + if (front>capacity-1) + { + front=0; + } + return true; + } + return false; + } + + /** Deletes an item from the rear of Deque. Return true if the operation is successful. */ + public bool DeleteLast() { + if (!IsEmpty()) + { + count--; + rear--; + if (rear<0) + { + rear=capacity-1; + } + return true; + } + return false; + } + + /** Get the front item from the deque. */ + public int GetFront() { + return IsEmpty()?-1:deque[front]; + } + + /** Get the last item from the deque. */ + public int GetRear() { + return IsEmpty()?-1:deque[rear]; + } + + /** Checks whether the circular deque is empty or not. */ + public bool IsEmpty() { + return count==0; + } + + /** Checks whether the circular deque is full or not. */ + public bool IsFull() { + return capacity==count; + } +} + +/** + * 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(); + */ +// @lc code=end + diff --git a/week01/66.plus-one.cs b/week01/66.plus-one.cs new file mode 100644 index 00000000..a8066db5 --- /dev/null +++ b/week01/66.plus-one.cs @@ -0,0 +1,38 @@ +/* + * @lc app=leetcode id=66 lang=csharp + * + * [66] Plus One + */ + +// @lc code=start +public class Solution { + public int[] PlusOne(int[] digits) { + //loop - + //if digits[i]<9 + //digits[i]=digits[i]+1; + //return + //digits[i]=0 + //handle exception case + + int i; + for (i = digits.Length-1; i >= 0; i--) + { + if(digits[i]<9) + { + digits[i]=digits[i]+1; + return digits; + } + digits[i]=0 ; + } + int[] result=new int [digits.Length+1]; + + if (i<0) + { + result[0]=1; + } + return result; + + } +} +// @lc code=end + diff --git a/week01/88.merge-sorted-array.cs b/week01/88.merge-sorted-array.cs new file mode 100644 index 00000000..a0c90376 --- /dev/null +++ b/week01/88.merge-sorted-array.cs @@ -0,0 +1,40 @@ +/* + * @lc app=leetcode id=88 lang=csharp + * + * [88] Merge Sorted Array + */ + +// @lc code=start +public class Solution { + public void Merge(int[] nums1, int m, int[] nums2, int n) { + //while (i>=0 &&j>=0) + //if nums[i]>nums[j] + //move nums[i] to tail + //else + // move nums[j] + //tail++ + //move remaining nums2 elements + int i=m-1; + int j=n-1; + int tail=m+n-1; + while (i>=0&&j>=0) + { + if (nums1[i]>nums2[j]) + { + nums1[tail--]=nums1[i];; + i--; + }else + { + nums1[tail--]=nums2[j];; + j--; + } + } + while (j>=0) + { + nums1[j]=nums2[j]; + j--; + } + } +} +// @lc code=end + diff --git a/week01/NOTE.md b/week01/NOTE.md index 50de3041..57e3899a 100644 --- a/week01/NOTE.md +++ b/week01/NOTE.md @@ -1 +1,137 @@ -学习笔记 \ No newline at end of file +# 学习笔记 + +1. Practise same question at least 5 times + +2. Data structure + + Linear + + Arrary + + Linked List + + Stack + + Queue + + Dictionary/Hash table? + + Non-linear + + Tree + + Graph +3. Algorithm + + if else + + for loop + + recursive + +4. Common Time Complexity [Table](https://www.bigocheatsheet.com/) + + O(1) + + O(log n) + example? + + O(n) + + O(nlogn) + ``` + for (int i=0; il1.val + tail.next=l1 + l1=l1.next + tail=tail.next + same thing for l2 +combine list (point tail.next to the list !=null) +``` + +# 4. Merge Sorted Array +Pseudocode +``` +while (i>=0 &&j>=0) + if nums[i]>nums[j] + move nums[i] to tail + else + move nums[j] + tail++ +move remaining nums2 elements +``` + +# 5. Two Sum +Pseudocode +``` + loop + check complement num in Hash + if yes return indexes + else add nums[i] to hash +``` +# 6 Move Zeroes +Pseudocode +``` + loop + if nums[i]!=0 + swap elements +``` + +# 7 Plus one +Pseudocode +``` + loop - + if digits[i]<9 + digits[i]=digits[i]+1; + return + digits[i]=0 +handle exception case +``` +# 8 Design Circular Deque +Take note: +InserFront + if (count == 1) rear = front; +# 9 Trapping Rain Water +Pseudocode +``` + loop n + set Left[i] + loop n + set right[i] + loop n + water+=min(max left i, max right i) +//Note: `Space complexity=O(n). This solution can be furhter optimized. +`` diff --git a/week02/1.two-sum.cs b/week02/1.two-sum.cs new file mode 100644 index 00000000..d65a6c4a --- /dev/null +++ b/week02/1.two-sum.cs @@ -0,0 +1,31 @@ +/* + * @lc app=leetcode id=1 lang=csharp + * + * [1] Two Sum + */ + +// @lc code=start +using System.Collections.Generic; + +public class Solution { + public int[] TwoSum(int[] nums, int target) { + //for + //if complement found in dict + // return indexes + //update index + + Dictionary dictionary=new Dictionary(); + for (int i = 0; i < nums.Length; i++) + { + int complement=target-nums[i]; + if (dictionary.ContainsKey(complement)) + { + return new int[]{i,dictionary[complement]}; + } + dictionary[nums[i]]=i; + } + return new int[]{-1,-1}; + } +} +// @lc code=end + diff --git a/week02/144.binary-tree-preorder-traversal.cs b/week02/144.binary-tree-preorder-traversal.cs new file mode 100644 index 00000000..deacc6e7 --- /dev/null +++ b/week02/144.binary-tree-preorder-traversal.cs @@ -0,0 +1,49 @@ +/* + * @lc app=leetcode id=144 lang=csharp + * + * [144] Binary Tree Preorder Traversal + */ + +// @lc code=start + +using System.Collections.Generic; +/** +* Definition for a binary tree node. +* public class TreeNode { +* public int val; +* public TreeNode left; +* public TreeNode right; +* public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) { +* this.val = val; +* this.left = left; +* this.right = right; +* } +* } +*/ +public class Solution { + public IList PreorderTraversal(TreeNode root) { + //build left most nodes in tree + //add result + //use current to travese + //current=pop + //current=popped.next + List result=new List(); + TreeNode current=root; + Stack stack=new Stack(); + while (current!=null||stack.Count>0) + { + while(current!=null) + { + result.Add(current.val); + stack.Push(current); + current=current.left; + } + current=stack.Pop(); + //result.Add(current.val); + current=current.right; + } + return result; + } +} +// @lc code=end + diff --git a/week02/242.valid anagram.cs b/week02/242.valid anagram.cs new file mode 100644 index 00000000..f0894d95 --- /dev/null +++ b/week02/242.valid anagram.cs @@ -0,0 +1,40 @@ +/* + * @lc app=leetcode id=242 lang=csharp + * + * [242] Valid Anagram + */ + +// @lc code=start +using System.Collections.Generic; + +public class Solution { + public bool IsAnagram(string s, string t) { + + //use array to track freq + //loop + //++ + //-- + if (s.Length!=t.Length) + { + return false; + } + int[] counters=new int[26]; + + for (int i = 0; i < s.Length; i++) + { + counters[s[i]-'a']++; + counters[t[i]-'a']--; + } + + foreach (var counter in counters) + { + if (counter!=0) + { + return false; + } + } + return true; + } +} +// @lc code=end + diff --git a/week02/264.ugly-number-ii.cs b/week02/264.ugly-number-ii.cs new file mode 100644 index 00000000..846a941c --- /dev/null +++ b/week02/264.ugly-number-ii.cs @@ -0,0 +1,42 @@ +/* + * @lc app=leetcode id=264 lang=csharp + * + * [264] Ugly Number II + */ + +// @lc code=start +using System; + +public class Solution { + public int NthUglyNumber(int n) { + + //Get min from array[i],array[j],array[k] + // //advanced min index + //use seperate if to remove duplicate + int[] result =new int[n]; + int index2=0; + int index3=0; + int index5=0; + result[0]=1; + for (int i = 1; i < n; i++) + { + int min=Math.Min(Math.Min(result[index2]*2,result[index3]*3), result[index5]*5); + if (min==result[index2]*2) + { + index2++; + } + if (min==result[index3]*3) + { + index3++; + } + if (min==result[index5]*5) + { + index5++; + } + result[i]=min; + } + return result[n-1]; + } +} +// @lc code=end + diff --git a/week02/347.top-k-frequent-elements.cs b/week02/347.top-k-frequent-elements.cs new file mode 100644 index 00000000..468ad575 --- /dev/null +++ b/week02/347.top-k-frequent-elements.cs @@ -0,0 +1,53 @@ +/* + * @lc app=leetcode id=347 lang=csharp + * + * [347] Top K Frequent Elements + */ + +// @lc code=start +using System.Collections.Generic; +public class Solution { + public int[] TopKFrequent(int[] nums, int k) { + + //create freq dict + //create list[] to hold numbers + //loop dict2 from end + //not null=> add result + Dictionary freqDict=new Dictionary(); + for (int i = 0; i < nums.Length; i++) + { + if (freqDict.ContainsKey(nums[i])) + { + freqDict[nums[i]]++; + } + else + { + freqDict.Add(nums[i],1); + } + } + + List[] bucket=new List[nums.Length+1]; + foreach (var item in freqDict) + { + if(bucket[item.Value]==null) + { + bucket[item.Value]=new List(); + } + bucket[item.Value].Add(item.Key); + } + + //int[] result=new int[k]; + List result=new List(); + for (int i = bucket.Length - 1; i >= 1 &&result.Count children; + + public Node() {} + + public Node(int _val) { + val = _val; + } + + public Node(int _val, IList _children) { + val = _val; + children = _children; + } +} +*/ + +using System.Collections.Generic; + +public class Solution { + public IList> LevelOrder(Node root) { + //use queue to explorer level + //while exploring add children to queue + + if(root==null) + return new List>(); + + Queue queue=new Queue(); + queue.Enqueue(root); + IList> result=new List>(); + while (queue.Count>0) + { + List levelResult=new List(); + int len= queue.Count; + for (int i = 0; i < len; i++) + { + Node node=queue.Dequeue(); + levelResult.Add(node.val); + foreach (var item in node.children) + { + queue.Enqueue(item); + } + } + result.Add(levelResult); + } + return result; + } +} +// @lc code=end + diff --git a/week02/49.group-anagrams.cs b/week02/49.group-anagrams.cs new file mode 100644 index 00000000..49b93c0b --- /dev/null +++ b/week02/49.group-anagrams.cs @@ -0,0 +1,46 @@ +/* + * @lc app=leetcode id=49 lang=csharp + * + * [49] Group Anagrams + */ + +// @lc code=start +using System; +using System.Collections.Generic; +using System.Text; + +public class Solution { + public IList> GroupAnagrams(string[] strs) { + //for strs + //compute freq string + //add to dict + Dictionary> dict = new Dictionary>(); + + foreach (var str in strs) + { + int[] freq=new int[26]; + foreach (var c in str) + { + freq[c-'a']++; + } + + StringBuilder freqStr=new StringBuilder(); + for (int i = 0; i < 26; i++) + { + freqStr.Append(freq[i]); + freqStr.Append("#"); + } + + if (!dict.ContainsKey(freqStr.ToString())) + { + dict.Add(freqStr.ToString(),new List()); + } + dict[freqStr.ToString()].Add(str); + } + + return new List>(dict.Values); + + } +} +// @lc code=end + diff --git a/week02/589.n-ary-tree-preorder-traversal.cs b/week02/589.n-ary-tree-preorder-traversal.cs new file mode 100644 index 00000000..7a35684c --- /dev/null +++ b/week02/589.n-ary-tree-preorder-traversal.cs @@ -0,0 +1,60 @@ +/* + * @lc app=leetcode id=589 lang=csharp + * + * [589] N-ary Tree Preorder Traversal + */ + +// @lc code=start +/* +// Definition for a Node. +public class Node { + public int val; + public IList children; + + public Node() {} + + public Node(int _val) { + val = _val; + } + + public Node(int _val,IList _children) { + val = _val; + children = _children; + } +} +*/ + +using System; +using System.Collections.Generic; + +public class Solution { + public IList Preorder(Node root) { + + //use stack to traverse + //push from right to left + if (root==null) + { + return new List(); + } + List result=new List(); + Stack stack=new Stack(); + stack.Push(root); + while (stack.Count>0) + { + Node popped=stack.Pop(); + result.Add(popped.val); + if (popped.children!=null) + { + for (int i = popped.children.Count - 1; i >= 0 ; i--) + { + stack.Push(popped.children[i]); + } + } + } + return result; + } + + +} +// @lc code=end + diff --git a/week02/94.binary-tree-inorder-traversal.cs b/week02/94.binary-tree-inorder-traversal.cs new file mode 100644 index 00000000..44c8b86f --- /dev/null +++ b/week02/94.binary-tree-inorder-traversal.cs @@ -0,0 +1,48 @@ +/* + * @lc app=leetcode id=94 lang=csharp + * + * [94] Binary Tree Inorder Traversal + */ + +// @lc code=start + +using System.Collections.Generic; +/** +* Definition for a binary tree node. +* public class TreeNode { +* public int val; +* public TreeNode left; +* public TreeNode right; +* public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) { +* this.val = val; +* this.left = left; +* this.right = right; +* } +* } +*/ +public class Solution { + public IList InorderTraversal(TreeNode root) { + //build left most nodes in tree + //use current to travese + //current=pop + //add to result + //current=popped.next + List result=new List(); + TreeNode current=root; + Stack stack=new Stack(); + while (current!=null||stack.Count>0) + { + while(current!=null) + { + stack.Push(current); + current=current.left; + } + current=stack.Pop(); + result.Add(current.val); + current=current.right; + } + return result; + } +} +// @lc code=end + diff --git a/week02/NOTE.md b/week02/NOTE.md index 50de3041..44e3a05f 100644 --- a/week02/NOTE.md +++ b/week02/NOTE.md @@ -1 +1,30 @@ -学习笔记 \ No newline at end of file +# 学习笔记 + +1. Hash table +- a speical data structure that can use key to access values +- use hash function to map key to index/hashcode + +2. Tree traversal (Depth first) +- pre-order +- In-order +- post-order + +2. Binary Tree +- Each node has at most two children + +3. Binary Search Tree + - parent's key> all keys in left subtree + - parent's key< all keys in right subtree + +4. Heap (complete tree) + - min heap => root's key < all keys in subtrees + - max heap => root's key > all keys in subtrees + +5. Heap Sort + - Steps + 1. Build a max heap + 2. Remove max and reduce the heap size by 1. Heapify the heap. (repeat while heap size>1) + https://www.geeksforgeeks.org/heap-sort + + + diff --git a/week03/105.construct-binary-tree-from-preorder-and-inorder-traversal.cs b/week03/105.construct-binary-tree-from-preorder-and-inorder-traversal.cs new file mode 100644 index 00000000..2e1fe693 --- /dev/null +++ b/week03/105.construct-binary-tree-from-preorder-and-inorder-traversal.cs @@ -0,0 +1,57 @@ +/* + * @lc app=leetcode id=105 lang=csharp + * + * [105] Construct Binary Tree from Preorder and Inorder Traversal + */ + +// @lc code=start + +using System; +using System.Collections.Generic; +/** +* Definition for a binary tree node. +* public class TreeNode { +* public int val; +* public TreeNode left; +* public TreeNode right; +* public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) { +* this.val = val; +* this.left = left; +* this.right = right; +* } +* } +*/ +public class Solution { + Dictionary inorderDict=new Dictionary(); + public TreeNode BuildTree(int[] preorder, int[] inorder) { + //use preorder to build + //use inorder to determine left subtree,right subtree + //create dict for inorder + for (int i = 0; i < inorder.Length; i++) + { + inorderDict[inorder[i]]=i; + } + TreeNode result=BuildTreeHelper(preorder,0,preorder.Length-1,0,inorder.Length-1); + + return result; + + } + + private TreeNode BuildTreeHelper(int[] preorder, int preLeft, int preRight, int inLeft, int inRight) + { + if (preLeft>preRight) + { + return null; + } + TreeNode root=new TreeNode(preorder[preLeft]); + int inorderIndex=inorderDict[root.val]; + int length=inorderIndex-inLeft; + + root.left=BuildTreeHelper(preorder,preLeft+1,preLeft+length,inLeft,inorderIndex-1); + root.right=BuildTreeHelper(preorder,preLeft+length+1,preRight,inorderIndex+1,inRight); + return root; + + } +} +// @lc code=end + diff --git a/week03/236.lowest-common-ancestor-of-a-binary-tree.cs b/week03/236.lowest-common-ancestor-of-a-binary-tree.cs new file mode 100644 index 00000000..1e53125d --- /dev/null +++ b/week03/236.lowest-common-ancestor-of-a-binary-tree.cs @@ -0,0 +1,40 @@ +/* + * @lc app=leetcode id=236 lang=csharp + * + * [236] Lowest Common Ancestor of a Binary Tree + */ + +// @lc code=start +/** + * Definition for a binary tree node. + * public class TreeNode { + * public int val; + * public TreeNode left; + * public TreeNode right; + * public TreeNode(int x) { val = x; } + * } + */ +public class Solution { + public TreeNode LowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { + + if (root==null||root==p||root==q) + { + return root; + } + TreeNode left=LowestCommonAncestor(root.left,p,q); + TreeNode right=LowestCommonAncestor(root.right,p,q); + if (left==null) + { + return right; + } + else if(right==null) + { + return left; + } + return root; + + } + +} +// @lc code=end + diff --git a/week03/46.Permutation.cs b/week03/46.Permutation.cs new file mode 100644 index 00000000..2e086189 --- /dev/null +++ b/week03/46.Permutation.cs @@ -0,0 +1,48 @@ +/* + * @lc app=leetcode id=46 lang=csharp + * + * [46] Permutations + */ + +// @lc code=start +using System; +using System.Collections.Generic; + +public class Solution { + public IList> Permute(int[] nums) { + //fill in n slot , create output=nums and swap + IList> result=new List>(); + List output=new List(nums); + int first=0; + PermuteHelper(nums.Length, output, first,result); + return result; + } + + private void PermuteHelper(int length, List output, int first, IList> result) + { + //terminator + if (first==length-1) + { + var tmpResult=new List(output); + result.Add(tmpResult); + return; + } + + for (int i = first; i < length; i++) + { + + Swap(output,first,i); + PermuteHelper(length,output,first+1,result); + Swap (output, first, i); + } + } + + private void Swap(List output, int indexA, int indexB) + { + int tmp=output[indexA]; + output[indexA]=output[indexB]; + output[indexB]=tmp; + } +} +// @lc code=end + diff --git a/week03/47.permutations-ii.cs b/week03/47.permutations-ii.cs new file mode 100644 index 00000000..93a24df0 --- /dev/null +++ b/week03/47.permutations-ii.cs @@ -0,0 +1,46 @@ +/* + * @lc app=leetcode id=47 lang=csharp + * + * [47] Permutations II + */ + +// @lc code=start +using System; +using System.Collections; +using System.Collections.Generic; + +public class Solution { + public IList> PermuteUnique(int[] nums) { + //sort array + //build output one by one + //use visited to remove duplicate + + Array.Sort(nums); + IList> result=new List>(); + PermuteHelper(nums,new Boolean[nums.Length],new List(),result); + + return result; + } + + private void PermuteHelper(int[] nums, bool[] visited, List output, IList> result) + { + //terminate + if (output.Count==nums.Length) + { + result.Add(new List(output)); + return; + } + for (int i = 0; i < nums.Length; i++) + { + if (visited[i]) continue; + if (i>0&&nums[i]==nums[i-1]&&!visited[i-1]) continue; + output.Add(nums[i]); + visited[i]=true; + PermuteHelper(nums,visited,output,result); + visited[i]=false; + output.RemoveAt(output.Count-1); + } + } +} +// @lc code=end + diff --git a/week03/77.combinations.cs b/week03/77.combinations.cs new file mode 100644 index 00000000..07cfff35 --- /dev/null +++ b/week03/77.combinations.cs @@ -0,0 +1,36 @@ +/* + * @lc app=leetcode id=77 lang=csharp + * + * [77] Combinations + */ + +// @lc code=start +using System; +using System.Collections.Generic; + +public class Solution { + public IList> Combine(int n, int k) { + //fill in n slot + var result=new List>(); + CombineHelper(new List(), result,1, n, k); + return result; + } + + private void CombineHelper(List output, List> result, int start, int n, int k) + { + if (output.Count==k) + { + result.Add(new List(output)); + return; + } + for (int i = start; i <=n ;i++) + { + output.Add(i); + CombineHelper(output,result,i+1,n,k);//i+1 + output.RemoveAt(output.Count-1);//faster than output.Remove(i); + + } + } +} +// @lc code=end + diff --git a/week03/DivideAndConquerTemplate.png b/week03/DivideAndConquerTemplate.png new file mode 100644 index 00000000..bf95973e Binary files /dev/null and b/week03/DivideAndConquerTemplate.png differ diff --git a/week03/NOTE.md b/week03/NOTE.md index 50de3041..6cc6c432 100644 --- a/week03/NOTE.md +++ b/week03/NOTE.md @@ -1 +1,29 @@ -学习笔记 \ No newline at end of file +学习笔记 + +1. Recursion + + - Similar to loop + - e.g. Climbing Stairs, Generate parenthesis + + - Template + + + +2. Divide and conquer + + Break problem into subproblems. + + Solve subproblems and merge result. + + e.g. Pow(x,n) + + Template + + image-2020110822150982 + + + +3. Backtracking + + - Evaluate all possible solutions/candidates. Abandon/backtrack as soon as candidate is invalid. + - e.g Generate parenthesis, subsets \ No newline at end of file diff --git a/week03/RecursionTemplate.png b/week03/RecursionTemplate.png new file mode 100644 index 00000000..96bcf91e Binary files /dev/null and b/week03/RecursionTemplate.png differ diff --git a/week04/122.best-time-to-buy-and-sell-stock-ii.cs b/week04/122.best-time-to-buy-and-sell-stock-ii.cs new file mode 100644 index 00000000..bd25612b --- /dev/null +++ b/week04/122.best-time-to-buy-and-sell-stock-ii.cs @@ -0,0 +1,23 @@ +/* + * @lc app=leetcode id=122 lang=csharp + * + * [122] Best Time to Buy and Sell Stock II + */ + +// @lc code=start +public class Solution { + public int MaxProfit(int[] prices) { + + int profit=0; + for (int i = 1; i < prices.Length; i++) + { + if (prices[i]>prices[i-1]) + { + profit+=prices[i]-prices[i-1]; + } + } + return profit; + } +} +// @lc code=end + diff --git a/week04/126.word-ladder-ii.cs b/week04/126.word-ladder-ii.cs new file mode 100644 index 00000000..5760d24c --- /dev/null +++ b/week04/126.word-ladder-ii.cs @@ -0,0 +1,88 @@ +/* + * @lc app=leetcode id=126 lang=csharp + * + * [126] Word Ladder II + */ + +// @lc code=start +using System.Collections.Generic; + +public class Solution { + public IList> FindLadders(string beginWord, string endWord, IList wordList) { + + IList> result=new List>(); + Queue> queue=new Queue>(); + HashSet visited=new HashSet(); + queue.Enqueue(new List(){beginWord}); + Dictionary> dict=new Dictionary>(); + foreach (var word in wordList) + { + for (int i = 0; i < word.Length; i++) + { + var key=word.Substring(0,i)+"*"+word.Substring(i+1); + if(!dict.ContainsKey(key)) dict[key]=new List(); + dict[key].Add(word); + } + } + bool found=false; + //bfs + while(queue.Count>0) + { + int levelCount=queue.Count; + HashSet tmpVisited=new HashSet(); + for (int i = 0; i < levelCount; i++) + { + //get path + //if peek last element==endword + //add result + + //if not found + //Get adjacents + //add subvisited + + var path=queue.Dequeue(); + var tmpLastWord=path[path.Count-1]; + if(tmpLastWord==endWord) + { + found=true; + result.Add(path); + }else + { + var adjacents=GetAdjacents(tmpLastWord,dict); + foreach (var adjacent in adjacents) + { + if(!visited.Contains(adjacent)) + { + //create new path + var newPath=new List(path); + newPath.Add(adjacent); + tmpVisited.Add(adjacent); + queue.Enqueue(newPath); + } + } + } + } + if(found) break; + //add visited + + foreach (var item in tmpVisited) + { + visited.Add(item); + } + } + return result; + } + + private List GetAdjacents(string tmpLastWord,Dictionary>dict) + { + var adjacents=new List(); + for (int i = 0; i < tmpLastWord.Length; i++) + { + var key=tmpLastWord.Substring(0,i)+"*"+tmpLastWord.Substring(i+1); + if(dict.ContainsKey(key)) adjacents.AddRange(dict[key]); + } + return adjacents; + } +} +// @lc code=end + diff --git a/week04/127.word-ladder.cs b/week04/127.word-ladder.cs new file mode 100644 index 00000000..c774bfac --- /dev/null +++ b/week04/127.word-ladder.cs @@ -0,0 +1,64 @@ +/* + * @lc app=leetcode id=127 lang=csharp + * + * [127] Word Ladder + */ + +// @lc code=start +using System; +using System.Collections.Generic; + +public class Solution { + public int LadderLength(string beginWord, string endWord, IList wordList) { + //create adjacentMap + //BFS + Dictionary> adjacentMap=new Dictionary>(); + foreach (var word in wordList) + { + for (int i = 0; i < word.Length; i++) + { + var key=word.Substring(0,i)+"*"+word.Substring(i+1); + if (!adjacentMap.ContainsKey(key)) + adjacentMap[key]=new List(); + adjacentMap[key].Add(word); + } + } + + HashSet visited=new HashSet(); + Queue> queue=new Queue>(); + queue.Enqueue(new Tuple(beginWord,1)); + visited.Add(beginWord); + while (queue.Count>0) + { + //pop node + //marked visited + //if ==, return + //else + //Get adjacent nodes + // + (string word, int level)=queue.Dequeue(); + if (word==endWord) return level; + for (int i = 0; i < word.Length; i++) + { + var key=word.Substring(0,i)+"*"+word.Substring(i+1); + if(adjacentMap.ContainsKey(key)) + { + foreach (var adjacent in adjacentMap[key]) + { + if (visited.Add(adjacent)) //not visited + { + if(word==adjacent) return level+1; + queue.Enqueue(new Tuple(adjacent,level+1)); + } + } + } + } + } + + return 0; + + + } +} +// @lc code=end + diff --git a/week04/153.find-minimum-in-rotated-sorted-array.cs b/week04/153.find-minimum-in-rotated-sorted-array.cs new file mode 100644 index 00000000..a72b7e54 --- /dev/null +++ b/week04/153.find-minimum-in-rotated-sorted-array.cs @@ -0,0 +1,24 @@ +/* + * @lc app=leetcode id=153 lang=csharp + * + * [153] Find Minimum in Rotated Sorted Array + */ + +// @lc code=start +public class Solution { + public int FindMin(int[] nums) { + //binary search + int start=0; + int end=nums.Length-1; + if(nums.Length==1||nums[0]nRow-1||j<0||j>nCol-1||grid[i][j]=='0') return; + + grid[i][j]='0'; + MarkZeroes(grid,i-1,j,nRow,nCol); + MarkZeroes(grid,i+1,j,nRow,nCol); + MarkZeroes(grid,i,j-1,nRow,nCol); + MarkZeroes(grid,i,j+1,nRow,nCol); + } +} +// @lc code=end + diff --git a/week04/33.search-in-rotated-sorted-array.cs b/week04/33.search-in-rotated-sorted-array.cs new file mode 100644 index 00000000..1635d059 --- /dev/null +++ b/week04/33.search-in-rotated-sorted-array.cs @@ -0,0 +1,34 @@ +/* + * @lc app=leetcode id=33 lang=csharp + * + * [33] Search in Rotated Sorted Array + */ + +// @lc code=start +public class Solution { + public int Search(int[] nums, int target) { + //binary search + int start=0; + int end=nums.Length-1; + int mid=0; + while (start<=end) + { + mid=(start+end)/2; + if(nums[mid]==target) return mid; + //mid in larger section + if(nums[start]<=nums[mid]) + { + if(nums[start]<=target&&targetfartest) fartest=i+nums[i]; + if(i==curEnd) + { + jump++; + curEnd=fartest; + } + + } + + return jump; + } + + +} +// @lc code=end + diff --git a/week04/455.assign-cookies.cs b/week04/455.assign-cookies.cs new file mode 100644 index 00000000..8b367cbc --- /dev/null +++ b/week04/455.assign-cookies.cs @@ -0,0 +1,27 @@ +/* + * @lc app=leetcode id=455 lang=csharp + * + * [455] Assign Cookies + */ + +// @lc code=start +using System; + +public class Solution { + public int FindContentChildren(int[] g, int[] s) { + //sort g and s + //for s + Array.Sort(g); + Array.Sort(s); + int gI=0; + int sI=0; + while (gI<=g.Length-1&&sI<=s.Length-1) + { + if(s[sI]>=g[gI])gI++; + sI++; + } + return gI; + } +} +// @lc code=end + diff --git a/week04/529.minesweeper.cs b/week04/529.minesweeper.cs new file mode 100644 index 00000000..cdd8145b --- /dev/null +++ b/week04/529.minesweeper.cs @@ -0,0 +1,68 @@ +/* + * @lc app=leetcode id=529 lang=csharp + * + * [529] Minesweeper + */ + +// @lc code=start +using System; + +public class Solution { + int[] dirX={-1,0,1,-1,1,-1,0,1}; + int[] dirY={-1,-1,-1,0,0,1,1,1}; + + public char[][] UpdateBoard(char[][] board, int[] click) { + //if M stop + // if E, dfs + int nRow=board.Length; + int nCol=board[0].Length; + int clickX=click[0]; + int clickY=click[1]; + if(board[clickX][clickY]=='M') + { + board[clickX][clickY]='X'; + } + else + { + dfs(board,clickX,clickY,nRow,nCol); + } + return board; + } + + private void dfs(char[][] board, int clickX, int clickY,int nRow,int nCol) + { + + //terminate + if(clickX<0||clickX>nRow-1||clickY<0||clickY>nCol-1) return; + + int count=0; + //only E + + for (int i = 0; i < 8; i++) + { + int x=clickX + dirX[i]; + int y=clickY + dirY[i]; + if(x<0||x>nRow-1||y<0||y>nCol-1) continue; + if(board[x][y]=='M') count++; + } + + if (count>0) + { + board[clickX][clickY]= (count.ToString())[0]; + } + else + { + board[clickX][clickY]='B'; + //dfs 8 directions + for (int i = 0; i < 8; i++) + { + int x=clickX + dirX[i]; + int y=clickY + dirY[i]; + if(x<0||x>nRow-1||y<0||y>nCol-1||board[x][y]!='E') continue; + dfs(board,x,y,nRow,nCol); + } + } + } +} +// @lc code=end + diff --git a/week04/55.jump-game.cs b/week04/55.jump-game.cs new file mode 100644 index 00000000..5b64a1ba --- /dev/null +++ b/week04/55.jump-game.cs @@ -0,0 +1,31 @@ +/* + * @lc app=leetcode id=55 lang=csharp + * + * [55] Jump Game + */ + +// @lc code=start +using System; + +public class Solution { + + private Boolean found=false; + public bool CanJump(int[] nums) { + //lastPos=nums.Length-1 + //for n-- + //if i+nums[i]>=lastPost + //lastPos=i + + int lastPos=nums.Length-1; + for (int i = nums.Length - 1; i >= 0 ; i--) + { + if(i+nums[i]>=lastPos) lastPos=i; + } + return lastPos==0; + + } + + +} +// @lc code=end + diff --git a/week04/74.search-a-2-d-matrix.cs b/week04/74.search-a-2-d-matrix.cs new file mode 100644 index 00000000..97135424 --- /dev/null +++ b/week04/74.search-a-2-d-matrix.cs @@ -0,0 +1,39 @@ +/* + * @lc app=leetcode id=74 lang=csharp + * + * [74] Search a 2D Matrix + */ + +// @lc code=start +public class Solution { + public bool SearchMatrix(int[][] matrix, int target) { + //binary search + + if (matrix.Length==0) return false; + + int nRow=matrix.Length; + int nCol=matrix[0].Length; + + int start=0; + int end=nRow*nCol-1; + int mid=0; + while (start<=end) + { + + mid=(start+end)/2; + var midElement=matrix[mid/nCol][mid%nCol]; + if (midElement==target) return true; + else if(target>midElement) + { + start=mid+1; + } + else + { + end=mid-1; + } + } + return false; + } +} +// @lc code=end + diff --git a/week04/860.lemonade-change.cs b/week04/860.lemonade-change.cs new file mode 100644 index 00000000..63506321 --- /dev/null +++ b/week04/860.lemonade-change.cs @@ -0,0 +1,33 @@ +/* + * @lc app=leetcode id=860 lang=csharp + * + * [860] Lemonade Change + */ + +// @lc code=start +public class Solution { + public bool LemonadeChange(int[] bills) { + + int five=0; + int ten=0; + foreach (var bill in bills) + { + if(bill==5)five++; + else if (bill==10) + { + if (five<0) return false; + five--; + ten++; + } + else //20 + { + if (ten>0&&five>0) {five--;ten--;} + else if(five>=3) five-=3; + else return false; + } + } + return true; + } +} +// @lc code=end + diff --git a/week04/874.walking-robot-simulation.cs b/week04/874.walking-robot-simulation.cs new file mode 100644 index 00000000..523a619d --- /dev/null +++ b/week04/874.walking-robot-simulation.cs @@ -0,0 +1,58 @@ +/* + * @lc app=leetcode id=874 lang=csharp + * + * [874] Walking Robot Simulation + */ + +// @lc code=start +using System; +using System.Collections.Generic; + +public class Solution { + public int RobotSim(int[] commands, int[][] obstacles) { + //0:N, 1:E, 2:S, 3:W + int x=0; + int y=0; + int direction=0; + int[,] forward=new int[,]{{0,1},{1,0},{0,-1},{-1,0}}; + int result=0; + //obstacles + HashSet obstaclesSet=new HashSet(); + foreach (var obs in obstacles) + { + //x+30000*2^16 + y+30000 + long code= ((long)(obs[0]+30000)<<16)+ (long)(obs[1]+30000); + obstaclesSet.Add(code); + } + //for loop + //if -2 set direction + //if -1 set direction + //else + //advance pos by 1 + //check pos in obstacle + //yes break + //no update pos + foreach (var command in commands) + { + if (command==-2) direction=(direction==0?3:direction-1); + else if (command==-1) direction=(direction==3?0:direction+1); + else + { + for (int i = 1; i <= command; i++) + { + int tmpX =x+forward[direction,0]; + int tmpY =y+forward[direction,1]; + long code=((long)(tmpX+30000)<<16)+ (long)(tmpY+30000); + if (obstaclesSet.Contains(code)) break; + x=tmpX; + y=tmpY; + result=Math.Max(result,x*x+y*y); + } + } + } + + return result; + } +} +// @lc code=end + diff --git a/week04/NOTE.md b/week04/NOTE.md index 50de3041..7fd1a2a8 100644 --- a/week04/NOTE.md +++ b/week04/NOTE.md @@ -1 +1,64 @@ -学习笔记 \ No newline at end of file +学习笔记 + +BFS + +- Explore nodes horizontally + +- Template + + - Add root to queue + - Add root to visited set + - While q!=empty + - v=q.dequeue() + - if v is goal return v + - foreach v's children + - if not visited + - add child to q + - add child to visited set + + + +DFS + +- Explore nodes vertically + +- Template + + - Add root to queue + + - dfs(root) + + - if root==null return; + - add root to visited set + - process current node + - foreach root's children + - if not visited + - dfs(child) + + + + Iteration version (Pending) + +Greedy algorithm + +- Making locally optimal choice at each stage + + + +使用二分查找,寻找一个半有序数组 [4, 5, 6, 7, 0, 1, 2] 中间无序的地方 + +​ + +```c# +int start=0; +int end=nums.Length-1; +if(nums.Length==1||nums[0]= 0 ; i--) + idleInterval-=Math.Min(counters[i],maxValue-1); + + return idleInterval>0?tasks.Length+idleInterval:tasks.Length; + } +} +// @lc code=end + diff --git a/week06/64.minimum-path-sum.cs b/week06/64.minimum-path-sum.cs new file mode 100644 index 00000000..23029641 --- /dev/null +++ b/week06/64.minimum-path-sum.cs @@ -0,0 +1,30 @@ +/* + * @lc app=leetcode id=64 lang=csharp + * + * [64] Minimum Path Sum + */ + +// @lc code=start +using System; + +public class Solution { + public int MinPathSum(int[][] grid) { + //dp[i][j]=min (dp[i-1][j],dp[i][j-1])+grid[i][j] + int nRow=grid.Length; + int nCol=grid[0].Length; + int[,] minPath=new int[nRow,nCol]; + for (int i = 0; i < nRow; i++) + { + for (int j = 0; j < nCol; j++) + { + if(i==0&&j==0) minPath[i,j]=grid[i][j]; + else if(i==0&&j>0) minPath[i,j]= minPath[i,j-1]+grid[i][j]; + else if (j==0) minPath[i,j]= minPath[i-1,j]+grid[i][j]; + else minPath[i,j]= Math.Min(minPath[i-1,j],minPath[i,j-1])+grid[i][j]; + } + } + return minPath[nRow-1,nCol-1]; + } +} +// @lc code=end + diff --git a/week06/647.palindromic-substrings.cs b/week06/647.palindromic-substrings.cs new file mode 100644 index 00000000..f92f92fd --- /dev/null +++ b/week06/647.palindromic-substrings.cs @@ -0,0 +1,32 @@ +/* + * @lc app=leetcode id=647 lang=csharp + * + * [647] Palindromic Substrings + */ + +// @lc code=start +public class Solution { + public int CountSubstrings(string s) { + //dp[i,j]=s[i]==sj[j]&&dp[i+1,j-1] + //if(s[i]==s[j]&&()) + if(s.Length==0) return 0; + int nRow=s.Length; + int nCol=s.Length; + bool[,] palindome=new bool[nRow,nCol]; + int count=0; + for (int j = 0; j < nCol; j++) + { + for (int i = 0; i <=j; i++) + { + if(s[i]==s[j]&&(j-i<=1||palindome[i+1,j-1])) + { + palindome[i,j]=true; + count++; + } + } + } + return count; + } +} +// @lc code=end + diff --git a/week06/72.edit-distance.cs b/week06/72.edit-distance.cs new file mode 100644 index 00000000..e6ee8702 --- /dev/null +++ b/week06/72.edit-distance.cs @@ -0,0 +1,38 @@ +/* + * @lc app=leetcode id=72 lang=csharp + * + * [72] Edit Distance + */ + +// @lc code=start +using System; + +public class Solution { + public int MinDistance(string word1, string word2) { + //if(word1[i]==word2[j]) dp[i,j] = dp[i-1,j-1]; + //else Max(insert,update,delete)+1 + //update => dp[i-1,j-1] + //insert => dp[i,j-1] + //delete => dp[i-1,j] + int[,] minOp=new int[word1.Length+1,word2.Length+1]; + for (int i = 0; i <= word1.Length; i++) + { + for (int j = 0; j <= word2.Length; j++) + { + if(i==0&&j==0) minOp[i,j]=0; + else if(i==0&&j>0) minOp[i,j]=minOp[i,j-1]+1; + else if(j==0&&i>0) minOp[i,j]=minOp[i-1,j]+1; + else //i>0&&j>0 + { + if(word1[i-1]==word2[j-1]) //take note + minOp[i,j]=minOp[i-1,j-1]; + else + minOp[i,j]= Math.Min(Math.Min(minOp[i-1,j-1],minOp[i,j-1]),minOp[i-1,j])+1; + } + } + } + return minOp[word1.Length,word2.Length]; + } +} +// @lc code=end + diff --git a/week06/91.decode-ways.cs b/week06/91.decode-ways.cs new file mode 100644 index 00000000..4f3ed756 --- /dev/null +++ b/week06/91.decode-ways.cs @@ -0,0 +1,45 @@ +/* + * @lc app=leetcode id=91 lang=csharp + * + * [91] Decode Ways + */ + +// @lc code=start +public class Solution { + public int NumDecodings(string s) { + //10.45 + //if s[i]==0 + //if s[i-1]==1,2 + //dp[i]=dp[i-2] + //else return 0 + //else if (s[i-1]==1||(s[i-1]==2&&s[i]>=1&&s[i]<=6)) + //dp[i]=dp[i-1] +dp[i-2] + //else + //dp[i]=dp[n-1] + + if(s.Length>=0&&s[0]=='0') return 0; + int max=1; + int first=1; + int second=1; + for (int i = 1; i < s.Length; i++) + { + if(s[i]=='0') + { + if(s[i-1]=='1'||s[i-1]=='2') + max=first; + else return 0; + } + else if (s[i-1]=='1'||(s[i-1]=='2'&&s[i]>='1'&&s[i]<='6')) + max=first+second; + else + max=second; + + first=second; + second=max; + } + return max; + } + +} +// @lc code=end + diff --git a/week06/NOTE.md b/week06/NOTE.md index 50de3041..a8778bb4 100644 --- a/week06/NOTE.md +++ b/week06/NOTE.md @@ -1 +1,23 @@ -学习笔记 \ No newline at end of file +学习笔记 + +Dynamic programming + +Break down a problem into subproblems (overlapping) + +Define state transition equation + +e.g. + +fib(n)=fib(n-1)+fib(n-2) + +(Longest common subsequence) + +​ if(text1[i-1]==text2[j-1]) dp[i,j]=dp[i-1,j-1]+1; +​ else dp[i,j]=Math.Max(dp[i,j-1],dp[i-1,j]); + +(Minimum Path Sum) + DP[i][j]=min(DP[i-1][j],DP[i,j-1])+grid[i,j] + +(Coin change) + + dp[i] = Math.Min(dp[i], dp[i - coins[j]] + 1); \ No newline at end of file diff --git a/week07/127.word-ladder.cs b/week07/127.word-ladder.cs new file mode 100644 index 00000000..e5237b59 --- /dev/null +++ b/week07/127.word-ladder.cs @@ -0,0 +1,63 @@ +/* + * @lc app=leetcode id=127 lang=csharp + * + * [127] Word Ladder + */ + +// @lc code=start +using System.Collections.Generic; + +public class Solution { + public int LadderLength(string beginWord, string endWord, IList wordList) { + + //2.11 + //bi bfs + //init beginset, endset + //while beginset !empty + //for word in beginset + //if == endword return level + //else + //get adjacent word + //set beginset and endset + + if(wordList.Contains(endWord)==false) return 0; + HashSet beginSet=new HashSet(); + HashSet endSet=new HashSet(); + HashSet visitedSet=new HashSet(); + HashSet wordSet=new HashSet(wordList); + beginSet.Add(beginWord); + endSet.Add(endWord); + int level=2; + while(beginSet.Count>0) + { + HashSet newSet=new HashSet(); + foreach(var word in beginSet) + { + //if(endSet.Contains(word)) return level; //take note + for(int i=0;iRank[parent2]) Parent[parent2]=parent1; + else Parent[parent1]=parent2; + Count--; + } + + public int Find(int n) + { + if(n==Parent[n]) return n; + while (Parent[n]!=n) + { + Parent[n]=Parent[Parent[n]]; //path compression + n=Parent[n]; + } + return n; + } +} +public class Solution { + public int FindCircleNum(int[][] M) { + UnionFind unionFind=new UnionFind(M.Length); + for (int i = 0; i < M.Length; i++) + { + for (int j = i+1; j < M.Length; j++) + { + if(M[i][j]==1) + unionFind.Union(i,j); + } + } + return unionFind.Count; + } +} +// @lc code=end + diff --git a/week07/NOTE.md b/week07/NOTE.md index 50de3041..c4066746 100644 --- a/week07/NOTE.md +++ b/week07/NOTE.md @@ -1 +1,56 @@ -学习笔记 \ No newline at end of file +学习笔记 + +Trie + +- ​ prefix tree. +- ​ a type of search tree +- ​ node stores partial key +- Template (pending) + + + +UnionFind + + - stores a collection of disjoint sets + - operations + - MakeSet + - Union + - Find + +Bidirectional BFS + +- Run two BFS + - One starts from initial state + - The other one starts from the goal + +Template + + beginSet={initial node} + + endSet={end node} + + level=2; + + While(beginSet != empty) + + newSet={} + + foreach node in beginSet + + foreach adjacent node + + if adjacent node in endSet return level/result + + else + + if (adjacent node not visited) add adjacent node to newSet + + if (newSet.Count0) + { + arr1[index] = num ; + counters[num]--; + index++; + } + } + for(int i=0; i0) + { + arr1[index] = i ; + counters[i]--; + index++; + } + } + return arr1; + } +} +// @lc code=end + diff --git a/week08/146.lru-cache.cs b/week08/146.lru-cache.cs new file mode 100644 index 00000000..81578ba7 --- /dev/null +++ b/week08/146.lru-cache.cs @@ -0,0 +1,146 @@ +/* + * @lc app=leetcode id=146 lang=csharp + * + * [146] LRU Cache + */ + +// @lc code=start +//6.18 +using System.Collections.Generic; + +public class Node +{ + public int value {set; get;} + public Node previous {set; get;} + public Node next {set; get;} + public Node (int value) + { + this.value = value; + } + +} +public class CustomedLinkedList +{ + private Node head; + private Node tail; + private Dictionary dict = new Dictionary(); + + public Node Last + { + get + { + if(dict.Count>0) + return tail.previous; + return null; + } + } + public CustomedLinkedList () + { + + head = new Node(-1); + tail = new Node(-1); + head.next=tail; + tail.previous=head; + } + + public void AddFirst(int value) + { + var tmp = head.next; + var newNode= new Node(value); + head.next=newNode; + newNode.next=tmp; + tmp.previous=newNode; + newNode.previous=head; + dict.Add(value,newNode); + + } + + public void RemoveLast() + { + if(dict.Count>0) + { + var last = tail.previous; + var secondLast = last.previous; + secondLast.next=tail; + tail.previous = secondLast; + dict.Remove(last.value); + } + } + + public void Remove(int value) + { + //Get node + if(dict.ContainsKey(value)) + { + + var node = dict[value]; + var previousNode=node.previous; + previousNode.next=node.next; + node.next.previous = previousNode; + //remove from dict + dict.Remove(value); + } + } + + +} +public class LRUCache { + private CustomedLinkedList keys = new CustomedLinkedList(); + private Dictionary cache = new Dictionary(); + + int capacity; + int count; + public LRUCache(int capacity) { + this.capacity = capacity; + count = 0; + } + + public int Get(int key) { + if (cache.ContainsKey(key)==false) return -1; + //remove the key + //add key to front + //return cache + keys.Remove(key); + keys.AddFirst(key); + return cache[key]; + } + + public void Put(int key, int value) { + if (cache.ContainsKey(key)==false) + { + //add key to front + //add value to cache + //check count + keys.AddFirst(key); + cache[key]=value; + count++; + if(count>capacity) + { + //remove last key + //remove cache + var last = keys.Last.value; + keys.RemoveLast(); + cache.Remove(last); + count--; + } + } + else + { + //update cache + //remove key + //add key to front + cache[key] = value; + keys.Remove(key); + keys.AddFirst(key); + } + } +} + +/** + * 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); + */ +// @lc code=end + diff --git a/week08/190.reverse-bits.cs b/week08/190.reverse-bits.cs new file mode 100644 index 00000000..9b152ade --- /dev/null +++ b/week08/190.reverse-bits.cs @@ -0,0 +1,24 @@ +/* + * @lc app=leetcode id=190 lang=csharp + * + * [190] Reverse Bits + */ + +// @lc code=start +public class Solution { + public uint reverseBits(uint n) { + //1.57 + //extract left most bit + int power=31; + uint result=0; + while(n!=0) + { + result+=((n&1)<>=1; + power--; + } + return result; + } +} +// @lc code=end + diff --git a/week08/191.number-of-1-bits.cs b/week08/191.number-of-1-bits.cs new file mode 100644 index 00000000..2b4929c7 --- /dev/null +++ b/week08/191.number-of-1-bits.cs @@ -0,0 +1,20 @@ +/* + * @lc app=leetcode id=191 lang=csharp + * + * [191] Number of 1 Bits + */ + +// @lc code=start +public class Solution { + public int HammingWeight(uint n) { + int count = 0; + while (n!=0) + { + count++; + n = (n & n-1); + } + return count; + } +} +// @lc code=end + diff --git a/week08/231.power-of-two.cs b/week08/231.power-of-two.cs new file mode 100644 index 00000000..e9ec6efc --- /dev/null +++ b/week08/231.power-of-two.cs @@ -0,0 +1,18 @@ +/* + * @lc app=leetcode id=231 lang=csharp + * + * [231] Power of Two + */ + +// @lc code=start +public class Solution { + public bool IsPowerOfTwo(int n) { + //0,1,2,3,4 + //1,2,4,8,16 + //clear left most 1 bit + if(n <= 0) return false; + return (n&(n-1)) == 0? true:false; + } +} +// @lc code=end + diff --git a/week08/NOTE.md b/week08/NOTE.md index 50de3041..cc63e2ec 100644 --- a/week08/NOTE.md +++ b/week08/NOTE.md @@ -1 +1,58 @@ -学习笔记 \ No newline at end of file +**Bitwise and shift operators** + +Bitwise complement ~ + +Left shift operator << + +Right shift operator >> + +Logical AND & + +Logical Or | + +Logical XOR ^ + + + +**Low level bit hacks** + +https://catonmat.net/low-level-bit-hacks + +1. x&1=> Extract rightmost bit + +2. x&(x-1) => Clear rightmost 1-bit + + + +**Bloom Filter** + + Probabilistic data structure. An element is either not in or **maybe** in the set + + Applications + +​ Cache filtering=> web caches of CDN + +​ Google Bigtable => use bloom filter to reduce the disk lookups for non-existent rows or columns + + + +**Sorting** + +**Simple Sort** + +1. Insertion sort +2. Selection sort +3. Bubble sort + +Efficient sorts + +1. Quicksort +2. Merge sort +3. Heapsort + +**Distribution Sort** + +1. Counting sort +2. Bucket sort +3. Radix sort + diff --git a/week09/300.longest-increasing-subsequence.cs b/week09/300.longest-increasing-subsequence.cs new file mode 100644 index 00000000..18119b99 --- /dev/null +++ b/week09/300.longest-increasing-subsequence.cs @@ -0,0 +1,33 @@ +/* + * @lc app=leetcode id=300 lang=csharp + * + * [300] Longest Increasing Subsequence + */ + +// @lc code=start +using System; + +public class Solution { + public int LengthOfLIS(int[] nums) { + //init dp[i] to 1 + //dp[i]= max(dp[j]) +1 => nums[i>nums[j] + + int[] localMax = new int[nums.Length]; + localMax[0]=1; + int max = 1; + for(int i=1; inums[j]) + localMax[i] = Math.Max(localMax[j]+1,localMax[i]); + } + max = Math.Max(max,localMax[i]); + } + return max; + + } +} +// @lc code=end + diff --git a/week09/32.longest-valid-parentheses.cs b/week09/32.longest-valid-parentheses.cs new file mode 100644 index 00000000..a5575947 --- /dev/null +++ b/week09/32.longest-valid-parentheses.cs @@ -0,0 +1,42 @@ +/* + * @lc app=leetcode id=32 lang=csharp + * + * [32] Longest Valid Parentheses + */ + +// @lc code=start +using System; +using System.Collections.Generic; + +public class Solution { + public int LongestValidParentheses(string s) { + + //s[i]=) + //s[i-1] =( + //dp[i]= dp[i-2] +2 + //else + //if s[i- dp[i-1]-1] =( + //dp[i] = dp[i-1]+2 +dp[i- dp[i-1]-1-1] + int[] dp = new int[s.Length]; + int max = 0; + for(int i=1; i=0?dp[i-2]+2:2; + } + else if((i- dp[i-1]-1)>=0&&(s[i- dp[i-1]-1]=='(')) + { + dp[i]= dp[i-1]+2+(i-dp[i-1]-2>=0?dp[i-dp[i-1]-2]:0); + } + max = Math.Max(max,dp[i]); + } + + } + return max; + } +} +// @lc code=end + diff --git a/week09/541.reverse-string-ii.cs b/week09/541.reverse-string-ii.cs new file mode 100644 index 00000000..423d3b11 --- /dev/null +++ b/week09/541.reverse-string-ii.cs @@ -0,0 +1,36 @@ +/* + * @lc app=leetcode id=541 lang=csharp + * + * [541] Reverse String II + */ + +// @lc code=start +using System; +using System.Text; + +public class Solution { + public string ReverseStr(string s, int k) { + char[] result = s.ToCharArray(); + for(int i=0; iRabin-Karp** + +use hash function to perform approximate check for each position. + +compare the whole pattern only when hash(pattern) = hash(substring) + +https://www.youtube.com/watch?v=H4VrKHVG5qI + + + +**KMP** + +https://www.educative.io/edpresso/what-is-the-knuth-morris-pratt-algorithm + + + +Unique Path II + +``` + if(obstacleGrid[i][j] == 1 ) + op[i,j] = 0; + else if(i==0&&j==0) + op[i,j] = 1; + else if (i==0) + op[i,j] = op[i,j-1]; + else if (j==0) + op[i,j] = op[i-1,j]; + else + op[i,j] = op[i,j-1] + op[i-1,j]; +``` + + + +​ + + + + + diff --git a/week10/NOTE.md b/week10/NOTE.md index 50de3041..33c66c12 100644 --- a/week10/NOTE.md +++ b/week10/NOTE.md @@ -1 +1,22 @@ -学习笔记 \ No newline at end of file +### 算法训练营毕业总结 + +之前参加过Coursera 的算法课程。虽然拿了证书,但是总觉得少了些什么。很多概念也忘了。 + +参加了训练营,才知道自己的短板。刚开始很多题目都不会做。原来同一给题目是需要刷很多遍地。 + +这个刻意练习的方法是很有效的。代码写的比以前简洁和漂亮多了。有一些Leetcode没看过的题目,我竟然也会做了。 + +很有意思的是,最近面试一间大公司,虽然没被录取,考题没看过,但是我会做。 + +这一次的训练营,目前我刷的题目是将近100题。我希望自己可以继续刷到300题,毕竟还有一些地方还不是那么熟练。 + +覃老师是一个很好的老师。让我对刻意练习有了更深一层的了解。还有同学门很努力的学习,助教老师的反馈,也带给我学习的动力。 + +最后,谢谢大家,让我们一起努力。 + + + + + + +