diff --git a/.gitignore b/.gitignore index 706fd07f..a35d2acf 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,4 @@ +*.DS_Store .idea .vscode +.vs diff --git "a/2019.04.27\347\272\277\344\270\212\347\255\224\347\226\221\350\246\201\347\202\271\346\225\264\347\220\206.pdf" "b/2019.04.27\347\272\277\344\270\212\347\255\224\347\226\221\350\246\201\347\202\271\346\225\264\347\220\206.pdf" new file mode 100644 index 00000000..631119e7 Binary files /dev/null and "b/2019.04.27\347\272\277\344\270\212\347\255\224\347\226\221\350\246\201\347\202\271\346\225\264\347\220\206.pdf" differ diff --git a/README.md b/README.md index d8906956..6838188c 100644 --- a/README.md +++ b/README.md @@ -17,6 +17,6 @@ ## 注意事项 -1. **代码文件命名规则:**`LeetCode_题目序号_学号`,比如学号为 `0` 的学员完成 [LeetCode 的第 2 题](https://leetcode.com/problems/add-two-numbers/description/) 后,请将代码文件名保存为 `LeetCode_2_0.py` (假设你使用的是 Python 语言)。 +1. **代码文件命名规则:**`LeetCode_题目序号_学号`,比如学号为 `0` 的学员完成 [LeetCode_33_108 的第 2 题](https://leetcode.com/problems/add-two-numbers/description/) 后,请将代码文件名保存为 `LeetCode_2_0.py` (假设你使用的是 Python 语言)。 2. **作业公布地址:** 我们会在置顶的 issue 中公布当周的算法练习题以及其他注意事项。 3. 如果对 Git 和 GitHub 不太了解,请参考 [Git 官方文档](https://git-scm.com/book/zh/v2) 或者极客时间的[《玩转 Git 三剑客》](https://time.geekbang.org/course/intro/145)视频课程。 diff --git a/Week_01/.DS_Store b/Week_01/.DS_Store new file mode 100644 index 00000000..44be00eb Binary files /dev/null and b/Week_01/.DS_Store differ diff --git a/Week_01/id_1/LeetCode_153_1.java b/Week_01/id_1/LeetCode_153_1.java new file mode 100644 index 00000000..6e66716b --- /dev/null +++ b/Week_01/id_1/LeetCode_153_1.java @@ -0,0 +1,35 @@ +class Solution { + public int findMin(int[] nums) { + int len = nums.length; + if (len == 1) { + return nums[0]; + } + + int min = 0; + int max = len - 1; + + if (nums[min] < nums[max]) { + return nums[min]; + } + + int mid = (min + max) / 2; + while (min <= max) { + if (nums[min] < nums[mid]) { + min = mid; + mid = (min + max) / 2; + }else if (nums[min] > nums[mid]){ + max = mid; + mid = (min + max) / 2; + }else { + break; + } + } + + if (min < len -1) { + if (nums[min] > nums[min + 1]) { + return nums[min + 1]; + } + } + return nums[min]; + } +} \ No newline at end of file diff --git a/Week_01/id_1/LeetCode24.java b/Week_01/id_1/LeetCode_24_1.java similarity index 100% rename from Week_01/id_1/LeetCode24.java rename to Week_01/id_1/LeetCode_24_1.java diff --git a/Week_01/id_1/LeetCode25.java b/Week_01/id_1/LeetCode_25_1.java similarity index 100% rename from Week_01/id_1/LeetCode25.java rename to Week_01/id_1/LeetCode_25_1.java diff --git a/Week_01/id_1/LeetCode_50_1.java b/Week_01/id_1/LeetCode_50_1.java new file mode 100644 index 00000000..fe34f24e --- /dev/null +++ b/Week_01/id_1/LeetCode_50_1.java @@ -0,0 +1,23 @@ +public class Solution { + double myPow(double x, int n) { + double result = this.pow(x, Math.abs(n)); + + if (n < 0) { + return 1/result; + } + return result; + } + + private double pow(double x, int n) { + if (n == 0) { + return 1; + } + double half = pow(x, n / 2); + if (n % 2 == 0) { + return half * half; + } else { + return half * half * x; + } + } +} + diff --git a/Week_01/id_1/LeetCode_698_1.java b/Week_01/id_1/LeetCode_698_1.java new file mode 100644 index 00000000..70a7e679 --- /dev/null +++ b/Week_01/id_1/LeetCode_698_1.java @@ -0,0 +1,56 @@ + +public class Solution { + + private int average; + private boolean[] mark; + public boolean canPartitionKSubsets(int[] nums, int k) { + + if (k == 1) { + return true; + } + + int sum = 0; + int len = nums.length; + + for (int i = 0; i < len; i ++) { + sum += nums[i]; + } + + if (sum % k != 0) { + return false; + } + + this.average = sum / k; + mark = new boolean[len]; + + return calSubSum(nums, 0, average, 0, k); + + } + + public boolean calSubSum(int[] nums, int curSum, int subSum, int start, int k) { + + if (k == 1) { + return true; + } + + if (curSum == subSum) { + return calSubSum(nums, 0, subSum, 0, k - 1); + } + + for (int i = start; i < nums.length; i ++) { + if (mark[i]) { + continue; + } + mark[i] = true; + + if (this.calSubSum(nums, curSum + nums[i], subSum, i + 1, k)) { + return true; + } + mark[i] = false; + } + return false; + + + } + +} diff --git a/Week_01/id_1/NOTE.md b/Week_01/id_1/NOTE.md index c684e62f..f0988620 100644 --- a/Week_01/id_1/NOTE.md +++ b/Week_01/id_1/NOTE.md @@ -1 +1,92 @@ -# 学习笔记 \ No newline at end of file +### 一. 第一周学习总结 + +#### 1. 关于链表题目的做题总结 + +做了作业中两道关于链表的题目,结合以前做的链表题目,发现自己用的方法基本有三种: + +- 遍历:链表和数组一样,基本的遍历是逃不了的,重点是怎么提高遍历效率的问题。 +- 反转:反转也是常用的方式,关于反转最主要的是记录三个节点:当前节点,当前节点的 prev 节点和 next 节点。整个反转过程就是这三个节点的不断变化。然后在反转的过程中可能需要做一些特殊的处理,比如本周的 LeetCode 24、25两道题目,都是要在反转的时候要讲前一组的尾节点的 next 指向本次反转后的头节点。 +- 快慢指针:包括查看链表是否有环,获取链表的中间节点等题目都可以用快慢指针的方式进行,当快指针到达末尾时,满指针刚好到达链表的中间,有环的话两者最终有机会相遇。 + + +#### 2. pow(x, n) 解题思路与递归简记 + +最先想到的就是循环相乘了,先暴力搞出来再说,代码如下 + +```Java + +public class Solution { + double myPow(double x, int n) { + int result = 1; + for (int i = 1; i <= n; i ++) { + result *= x; + } + return result; + } +} +``` + +这种解法时间复杂度为 O(N),实际提交可能会超时,因此需要改进。这里用到数学知识: + +> a^m * a^n = a^(m+n) + +因此以 2 的 10 次方为例: + +``` +2^10 = 2^5 * 2^5 +2^5 = 2^2 * 2^2 * 2 +2^2 = 2^1 * 2^1 +2^1 = 2^0 * 2 +``` + +因此每一个指数幂的计算都可以进行折半计算,这样就可以通过递归的形式进行计算。 + +递归公式为: + +``` +n 为偶数: x^n = x^(n/2) * x^(n/2) +n 为奇数: x^n = x^(n/2) * x^(n/2) * x +``` + +终止条件为: + +``` +n = 0, x^0 = 1 +``` + +实现代码如下: + +```Java +public class Solution { + double myPow(double x, int n) { + + double result = this.pow(x, Math.abs(n)); + + if (n < 0) { + return -n; + } + return n; + } + + private double pow(double x, int n) { + if (n == 0) { + return 1; + } + double half = pow(x, n / 2); + if (n % 2 == 0) { + return half * half; + } else { + return half * half * x; + } + } +} +``` + +最终返回结果要考虑 n 为负数的情况,因此先取绝对值进行计算,如果为负数则返回计算结果的倒数。整个算法的复杂度由 O(N) 变为了 O(logN)。 + +关于递归最重要的还是要找到递归公式,如王争老师在专栏中提到的三步: + +- 分解出子问题,子问题的解题思路通用:这里的 a^m * a^n = a^(m+n) 就是典型的案例。 +- 递归过程的计算:每次计算的结果是子问题的结果汇总,这里就是指数为奇数和偶数时的不同的计算公式。 +- 终止条件:这里的终止条件就是幂为 0 的时候。 + diff --git a/Week_01/id_100/LeetCode_21_100.java b/Week_01/id_100/LeetCode_21_100.java new file mode 100644 index 00000000..4f6c6d30 --- /dev/null +++ b/Week_01/id_100/LeetCode_21_100.java @@ -0,0 +1,29 @@ +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode(int x) { val = x; } + * } + */ +class Solution { + public ListNode mergeTwoLists(ListNode n1, ListNode n2) { + ListNode result = new ListNode(0); + ListNode n0 = result; + while (n1 != null && n1 != null) { + //System.out.println("n1-----" + n1.val + "--------n2-------" + n2.val + if (n1.val < n2.val) { + n0.next = new ListNode(n1.val); + n1 = n1.next; + } else { + n0.next = new ListNode(n2.val); + n2 = n2.next; + } + + n0 = n0.next; + } + if(n1 != null) n0.next = n1; + else n0.next = n2; + return result.next; + } +} diff --git a/Week_01/id_100/LeetCode_83_100.java b/Week_01/id_100/LeetCode_83_100.java new file mode 100644 index 00000000..179b3557 --- /dev/null +++ b/Week_01/id_100/LeetCode_83_100.java @@ -0,0 +1,28 @@ +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode(int x) { val = x; } + * } + */ +class Solution { + public ListNode deleteDuplicates(ListNode head) { + ListNode pre = head; + ListNode pre_next = pre.next; + if(pre == null || pre_next == null){ + return head; + } + while(pre_next != null){ + if(pre.val == pre_next.val){ + pre_next = pre_next.next; + pre = pre_next; + }else{ + pre = pre_next; + pre_next = pre_next.next; + } + } + return head; + + } +} diff --git a/Week_01/id_101/LeetCode_141_101.java b/Week_01/id_101/LeetCode_141_101.java new file mode 100644 index 00000000..8a31d024 --- /dev/null +++ b/Week_01/id_101/LeetCode_141_101.java @@ -0,0 +1,26 @@ +package linkedlist.linkedListCycle; + +import linkedlist.ListNode; + +/** + * @author Seina + * @version 2019-01-14 20:37:52 + */ +public class LinkedListCycle { + + public boolean hasCycle(ListNode head) { + if (head == null || head.next == null){ + return false; + } + ListNode fast = head; + ListNode low = head; + while (fast != null && fast.next != null){ + fast = fast.next.next; + low = low.next; + if (fast == low){ + return true; + } + } + return false; + } +} \ No newline at end of file diff --git a/Week_01/id_101/LeetCode_142_101.java b/Week_01/id_101/LeetCode_142_101.java new file mode 100644 index 00000000..e5eff175 --- /dev/null +++ b/Week_01/id_101/LeetCode_142_101.java @@ -0,0 +1,43 @@ +package linkedlist.linkedListCycleII; + +import linkedlist.ListNode; + +/** + * @author Seina + * @version 2019-01-15 21:07:00 + * + * 判断链表是否有环,如果有,返回入环结点 + */ +public class LinkedListCycleII { + public ListNode detectCycle(ListNode head) { + if (head == null || head.next == null){ + return null; + } + ListNode fast = head; + ListNode low = head; + + //标识是否有环 + boolean hasCycle = false; + while (fast != null && fast.next != null){ + fast = fast.next.next; + low = low.next; + if (fast == low){ + hasCycle = true; + break; + } + } + + //如果有环,求出入环结点 + if (hasCycle){ + fast = head; + while (fast != low){ + fast = fast.next; + low = low.next; + } + return low; + } + + ///如果没有环,返回null + return null; + } +} \ No newline at end of file diff --git a/Week_01/id_101/LeetCode_206_101.java b/Week_01/id_101/LeetCode_206_101.java new file mode 100644 index 00000000..ddcf2865 --- /dev/null +++ b/Week_01/id_101/LeetCode_206_101.java @@ -0,0 +1,43 @@ +package linkedlist.reverseList; + +import linkedlist.ListNode; + +/** + * @author Seina + * @version 2019-01-03 23:26:18 + * + * 定义一个函数,输入一个链表的第一个结点,反转该链表并输出反转后链表的第一个结点。 + */ +public class ReverseList { + + /** + * 迭代法 + * @param head :头结点 + * @return + */ + public ListNode reverseList1(ListNode head){ + + if (head == null || head.next == null) { + return head; + } + + ListNode pre= null; + ListNode cur = head; + ListNode next; + + while (cur != null){ + //将当前结点指向的下一个结点存起来赋值给next结点 + next = cur.next; + //开始改变当前结点的指针-->指向上一个结点 + cur.next = pre; + //开始移动指针,pre --> 移动到 cur + pre = cur; + //cur移动到最先存好的next + cur = next; + } + + return pre; + } + + +} \ No newline at end of file diff --git a/Week_01/id_101/LeetCode_20_101.java b/Week_01/id_101/LeetCode_20_101.java new file mode 100644 index 00000000..9aa373ce --- /dev/null +++ b/Week_01/id_101/LeetCode_20_101.java @@ -0,0 +1,44 @@ +package stack.validParentheses; + +/** + * @author Seina + * @version 2019-01-25 20:58:04 + * + * LeetCode20:有效的括号 + */ +public class ValidParentheses { + public static boolean isValid(String s) { + if(s == null || s.length() == 1) return false; + if(s.length() == 0) return true; + + //toCharArray声明了一个字符串长度那么大的数组arr + char[] arr = s.toCharArray(); + if (arr[0] == ')' || arr[0] == ']' || arr[0] == '}') return false; + + //又声明了一个比字符串长度大1的数组stack(可以理解成底层是数组实现的顺序栈) + int[] stack = new int[arr.length+1]; + int ptr = 0; + + //开始遍历数组arr + for (int i = 0; i < arr.length; i++) { + int val = 0; + switch(arr[i]){ + case '(':val = -1;break; + case ')':val = 1;break; + case '[':val = -2;break; + case ']':val = 2;break; + case '{':val = -3;break; + case '}':val = 3;break; + default:break; + } + if(stack[ptr] + val == 0){ + stack[ptr--] = 0; + }else{ + stack[++ptr] = val; + } + } + return stack[1] == 0; + } + + +} \ No newline at end of file diff --git a/Week_01/id_101/LeetCode_24_101.java b/Week_01/id_101/LeetCode_24_101.java new file mode 100644 index 00000000..92fe17d7 --- /dev/null +++ b/Week_01/id_101/LeetCode_24_101.java @@ -0,0 +1,35 @@ +package linkedlist.swapNodesInPairs; + +import linkedlist.ListNode; + +/** + * @author Seina + * @version 2019-01-16 22:35:25 + */ +public class SwapNodesInPairs { + + public ListNode swapPairs(ListNode head) { + + if (head == null || head.next == null) { + return head; + } + + ListNode root = new ListNode(); + root.next = head; + ListNode pre = root; + ListNode a; + ListNode b; + + //a和b都不为空,才进入循环进行两两交换,并移动pre + while (pre.next != null && pre.next.next != null) { + a = pre.next; + b = a.next; + pre.next = b; + a.next = b.next; + b.next = a; + pre = a; + } + return root.next; + } + +} \ No newline at end of file diff --git a/Week_01/id_101/LeetCode_25_101.java b/Week_01/id_101/LeetCode_25_101.java new file mode 100644 index 00000000..accf5453 --- /dev/null +++ b/Week_01/id_101/LeetCode_25_101.java @@ -0,0 +1,58 @@ +package linkedlist.reverseNodesInkGroup; + +import linkedlist.ListNode; + +/** + * @author Seina + * @version 2019-01-20 18:50:06 + */ +public class ReverseNodesInkGroup { + + /** + * + * @param head 链表第一个结点 + * @param k:是一个正整数,他的值小于或等于链表的长度 + * @return 反转后的链表第一个结点 + */ + public ListNode reverseKGroup(ListNode head, int k) { + //k等于1,每1个结点进行翻转,相当于直接返回原始链表 + if (k < 2) { + return head; + } + ListNode start; + ListNode pre = null; + ListNode cur = head; + ListNode next; + int count = 1; + while (cur != null) { + next = cur.next; + if (count == k) { + start = pre == null ? head : pre.next; + //head用来追踪链表反转过程中的第一个结点 + head = pre == null ? cur : head; + resign(pre, start, cur, next); + pre = start; + count = 0; + } + count++; + cur = next; + } + return head; + } + private void resign(ListNode left, ListNode start, ListNode end, + ListNode right) { + ListNode p = start; + ListNode c = start.next; + ListNode n; + while (c != right) { + n = c.next; + c.next = p; + p = c; + c = n; + } + if (left != null) { + left.next = end; + } + start.next = right; + } +} \ No newline at end of file diff --git a/Week_01/id_101/NOTE.md b/Week_01/id_101/NOTE.md index c684e62f..3d9d4ec1 100644 --- a/Week_01/id_101/NOTE.md +++ b/Week_01/id_101/NOTE.md @@ -1 +1 @@ -# 学习笔记 \ No newline at end of file +[关于递归的一篇总结文章](https://blog.csdn.net/weixin_38118016/article/details/89368351) diff --git a/Week_01/id_104/LeetCode_20_104.java b/Week_01/id_104/LeetCode_20_104.java new file mode 100644 index 00000000..fadddddf --- /dev/null +++ b/Week_01/id_104/LeetCode_20_104.java @@ -0,0 +1,69 @@ +class Solution { + + private Map charMap=new HashMap(); + public boolean isValid(String s) { + + //1.拆成数组 + //2.从头遍历数组 往栈里插入 + //3.记录最后一个入栈的字符 和 当前入栈的字符 比较是否可以消除 + // 3.1 可以消除 出栈 + // 3.2 不可以消除 继续入栈 记录当前入栈字符为最后一次入栈字符 + //4.数组遍历结束后 检查栈的长度是否为0 为0则true 否则false + // 使用栈的数据结构 先入后出 + //3. + if(s==null){ + return false; + } + if("".equals(s)){ + return true; + } + initMap(charMap); + + Stack stack=new Stack(); + char stackTopStr; + char str; + for(int i=0;i map){ + map.put('(',')'); + map.put('{','}'); + map.put('[',']'); + map.put('"','"'); + } + + /** + * 是否可从栈中移除 + * stackTopStr 栈顶元素 + * waitInStackStr 即将入栈元素 + **/ + private boolean canPop(Map map,char stackTopStr,char waitInStackStr){ + boolean pop=false; + Character v=map.get(stackTopStr); + if(v!=null){ + pop=(v==waitInStackStr); + } + return pop; + } +} \ No newline at end of file diff --git a/Week_01/id_104/LeetCode_242_104.java b/Week_01/id_104/LeetCode_242_104.java new file mode 100644 index 00000000..abdd5c28 --- /dev/null +++ b/Week_01/id_104/LeetCode_242_104.java @@ -0,0 +1,31 @@ +class Solution { + public boolean isAnagram(String s, String t) { + // 1.判断两个字符长度是否相等 不等返回false + if(s==null && t==null ){ + return true; + } + if(s==null || t==null){ + return false; + } + + if(s.length()!=t.length()){ + return false; + } + boolean result=true; + int[] sAry=new int[26]; + int[] tAry=new int[26]; + for(int i=0;i sets=new HashSet(); + if(head==null){ + return head; + } + ListNode cur=head; + while(cur.next!=null){ + //将当前元素值 存在Set集合里 进行判重 + sets.add(cur.val); + //3 判断下个元素是否已经在map中存在 如果存在则删除此元素 + if(sets.contains(cur.next.val)){ + cur = removeNextNode(cur); + } + if(cur==null){ + //异常数据 跳出循环 + break; + } + cur=cur.next; + } + //4 打印最后的对象 + ListNode printNode=head; + while(printNode!=null){ + System.out.println(printNode.val); + printNode=printNode.next; + } + return head; + } + + /** + * 删除下一个元素 + * node 当前元素 + **/ + private ListNode removeNextNode(ListNode node){ + if(node==null){ + return null; + } + if(nodex.next==null){ + return node; + } + node.next=nodex.next.next; + return node; + + } +} \ No newline at end of file diff --git a/Week_01/id_104/LeetCode_905_104.java b/Week_01/id_104/LeetCode_905_104.java new file mode 100644 index 00000000..bb44d8f0 --- /dev/null +++ b/Week_01/id_104/LeetCode_905_104.java @@ -0,0 +1,30 @@ +class Solution { + + public int[] sortArrayByParity(int[] A) { + if(A==null){ + return A; + } + // 记录数组两个指针位置 i,j + + int i=0; + int j=A.length-1; + int tmp; + // i是从开始慢慢递增,j是从末尾慢慢递减 + // 如果i nums[1] ? nums[1] : nums[0]; + } + if(nums[0] < nums[nums.length-1]){ + return nums[0]; + } + int min = 0; + int high = nums.length - 1; + int mid = 0; + while(min <= high){ + //针对1、2、3这种情况 + if(min == high){ + return nums[min]; + } + mid = min + ((high-min) >> 1); + if(nums[mid] > nums[high]){ + if(nums[mid+1] < nums[mid]){ + return nums[mid+1]; + } + min = mid + 1; + continue; + } + if(nums[mid] < nums[min]){ + if(nums[mid-1] > nums[mid]){ + return nums[mid]; + } + high = mid - 1; + } + } + return -1; + } + + //二分查找 + //分为两种情况 + //mid比最后一个元素大,判断它右边的值是否小于它,如果小于的话就返回右边的值,否则的话,min取mid+1 + //mid比第一个元素小,判断它左边的值是否比它大,如果大的话,直接返回它自己,否则的话high取mid-1 + } + + class Solution2 { + public int findMin(int[] nums) { + if(nums.length == 1){ + return nums[0]; + } + int min = 0; + int high = nums.length - 1; + int mid = 0; + while(min < high){ + mid = min + ((high-min) >> 1); + if(nums[mid] > nums[high]){ + min = mid + 1; + } else { + high = mid; + } + } + return nums[min]; + } + + //二分查找 + //分为两种情况 + //mid比最后一个元素大,判断它右边的值是否小于它,如果小于的话就返回右边的值,否则的话,min取mid+1 + //mid比第一个元素小,判断它左边的值是否比它大,如果大的话,直接返回它自己,否则的话high取mid-1 + + + } +} diff --git a/Week_01/id_108/LeetCode_20_108.java b/Week_01/id_108/LeetCode_20_108.java new file mode 100644 index 00000000..aafe9ceb --- /dev/null +++ b/Week_01/id_108/LeetCode_20_108.java @@ -0,0 +1,49 @@ +import org.junit.Test; + +import java.util.Stack; + +/** + * @author zhangruihao.zhang + * @version v1.0.0 + * @since 2019/04/29 + */ +public class LeetCode_20_108 { + public static void main(String[] args) { + String str = "()[]{}"; + System.out.println(isValid(str)); + } + public static boolean isValid(String s) { + Stack stack = new Stack(); + for(int i=0;i target){ + //target处于旋转的后半段 + return binarySerach(nums,min,end,target); + }else{ + //target有可能处于旋转的前半段 + return binarySerach(nums,0,min-1,target); + } + } + + //查找旋转点 + private int min(int[] nums){ + int low = 0; + int high = nums.length - 1; + int mid; + while(low < high){ + mid = low + ((high-low)>>1); + if(nums[mid]>nums[high]){ + low = mid + 1; + }else{ + high = mid; + } + } + return low; + } + + //二分查找 + private int binarySerach(int[] nums,int left,int right,int target){ + int mid = 0; + while(left>1); + if(nums[mid]==target){ + return mid; + } + if(nums[mid]target){ + right = mid - 1; + continue; + } + } + if(nums[left] == target){ + return left; + } + return -1; + } + } +} diff --git a/Week_01/id_108/LeetCode_503_108.java b/Week_01/id_108/LeetCode_503_108.java new file mode 100644 index 00000000..1f98abff --- /dev/null +++ b/Week_01/id_108/LeetCode_503_108.java @@ -0,0 +1,33 @@ +import java.util.Stack; + +/** + * @author zhangruihao.zhang + * @version v1.0.0 + * @since 2019/04/29 + */ +public class LeetCode_503_108 { + class Solution { + public int[] nextGreaterElements(int[] nums) { + + Stack stack = new Stack<>(); + int index[] = new int[nums.length]; + for (int i = 0; i < index.length; i++) { + index[i] = -1; + } + if (nums.length == 1) { + return index; + } + int count = 0; + while (count < 2) { + for (int i = 0; i < nums.length; i++) { + while (!stack.isEmpty() && nums[i] > nums[stack.peek()]) { + index[stack.pop()] = nums[i]; + } + stack.push(i); + } + count++; + } + return index; + } + } +} diff --git a/Week_01/id_108/LeetCode_687_108.java b/Week_01/id_108/LeetCode_687_108.java new file mode 100644 index 00000000..295b6383 --- /dev/null +++ b/Week_01/id_108/LeetCode_687_108.java @@ -0,0 +1,50 @@ +/** + * @author zhangruihao.zhang + * @version v1.0.0 + * @since 2019/05/03 + */ +public class LeetCode_687_108 { + /** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ + class Solution { + int maxLen = 0; + public int longestUnivaluePath(TreeNode root) { + if(root == null){ + return 0; + } + longest(root); + return maxLen; + } + + private int longest(TreeNode root){ + if(root == null){ + return 0; + } + int leftLen=longest( root.left); + int rightLen=longest( root.right); + int leftUnivalueLen = 0; + int rightUnivalue = 0; + if(root.left != null && root.left.val == root.val){ + leftUnivalueLen = leftLen + 1; + } + + if(root.right != null && root.right.val == root.val){ + rightUnivalue = rightLen + 1; + } + + maxLen = max(maxLen , leftUnivalueLen + rightUnivalue ); + return max(leftUnivalueLen,rightUnivalue); + } + + private int max(int x,int y){ + return x>y ? x : y; + } + } +} diff --git a/Week_01/id_108/LeetCode_698_108.java b/Week_01/id_108/LeetCode_698_108.java new file mode 100644 index 00000000..ec86aeef --- /dev/null +++ b/Week_01/id_108/LeetCode_698_108.java @@ -0,0 +1,60 @@ +import java.util.Arrays; + +/** + * @author zhangruihao.zhang + * @version v1.0.0 + * @since 2019/05/04 + */ +public class LeetCode_698_108 { + //这道题没调出来,看的别人的答案 + class Solution { + public boolean canPartitionKSubsets(int[] nums, int k) { + //因为题目限制条件不用担心溢出 + int sum = 0; + for(int i = 0; i < nums.length; i++){ + sum += nums[i]; + } + if(sum % k != 0){ + return false; + } + //求出子集的和 + sum = sum / k; + //排序 小的放最前面大的放最后面 + Arrays.sort(nums); + //如果子集的和小于数组最大的直接返回false + if(nums[nums.length - 1] > sum){ + return false; + } + //建立一个长度为k的桶 + int[] arr = new int[k]; + //桶的每一个值都是子集的和 + Arrays.fill(arr, sum); + //从数组最后一个数开始进行递归 + return help(nums, nums.length - 1, arr, k); + } + + boolean help(int[] nums, int cur, int[] arr, int k){ + //已经遍历到了-1说明前面的所有数都正好可以放入桶里,那所有桶的值此时都为0,说明找到了结果,返回true + if(cur < 0){ + return true; + } + //遍历k个桶 + for(int i = 0; i < k; i++){ + //如果正好能放下当前的数或者放下当前的数后,还有机会继续放前面的数(剪枝) + if(arr[i] == nums[cur] || (cur > 0 && arr[i] - nums[cur] >= nums[0])){ + //放当前的数到桶i里 + arr[i] -= nums[cur]; + //开始放下一个数 + if(help(nums, cur - 1, arr, k)){ + return true; + } + //这个数不该放在桶i中 + //从桶中拿回当前的数 + arr[i] += nums[cur]; + } + } + return false; + } + + } +} diff --git a/Week_01/id_108/LeetCode_83_108.java b/Week_01/id_108/LeetCode_83_108.java new file mode 100644 index 00000000..6eb13ec4 --- /dev/null +++ b/Week_01/id_108/LeetCode_83_108.java @@ -0,0 +1,35 @@ +/** + * @author zhangruihao.zhang + * @version v1.0.0 + * @since 2019/04/20 + */ +public class LeetCode_83_108 { + /** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode(int x) { val = x; } + * } + */ + class Solution { + public ListNode deleteDuplicates(ListNode head) { + if(head == null || head.next == null){ + return head; + } + ListNode pre = head; + ListNode tmp = head.next; + while(pre != null){ + if(tmp != null && pre.val == tmp.val){ + pre.next = tmp.next; + tmp.next = null; + tmp = pre.next; + } else { + pre = pre.next; + tmp = pre != null ? pre.next : null; + } + } + return head; + } + } +} diff --git a/Week_01/id_108/LeetCode_895_108.java b/Week_01/id_108/LeetCode_895_108.java new file mode 100644 index 00000000..fc188a29 --- /dev/null +++ b/Week_01/id_108/LeetCode_895_108.java @@ -0,0 +1,83 @@ +import org.junit.Test; + +import java.util.HashMap; +import java.util.PriorityQueue; + +/** + * @author zhangruihao.zhang + * @version v1.0.0 + * @since 2019/05/03 + */ +public class LeetCode_895_108 { + + class FreqStack { + + private PriorityQueue queue = null; + private HashMap itemCountMap = null; + private int count; + + public FreqStack() { + itemCountMap = new HashMap<>(); + queue = new PriorityQueue<>((o1, o2) -> + o1.getCount().compareTo(o2.getCount()) == 0 ? + -o1.getOrder().compareTo(o2.getOrder()) : -o1.getCount().compareTo(o2.getCount())); + } + + public void push(int x) { + count ++; + itemCountMap.put(x, itemCountMap.getOrDefault(x, 0) + 1); + queue.offer(new Pair(x, count, itemCountMap.getOrDefault(x, 0) + 1)); + } + + public int pop() { + Pair peek = queue.poll(); + int item = peek == null ? -1 : peek.item; + Integer integer = itemCountMap.get(item); + if(integer == 1){ + itemCountMap.remove(item); + }else { + itemCountMap.put(item, itemCountMap.get(item) - 1); + } + return item; + } + + private class Pair { + private int item; + //添加入队的顺序 + private Integer order; + //共有几个相同的元素 + private Integer count; + + public Pair(int item, Integer order, Integer count) { + this.item = item; + this.order = order; + this.count = count; + } + + public int getItem() { + return item; + } + + public void setItem(int item) { + this.item = item; + } + + public Integer getOrder() { + return order; + } + + public void setOrder(Integer order) { + this.order = order; + } + + public Integer getCount() { + return count; + } + + public void setCount(Integer count) { + this.count = count; + } + } + } + +} diff --git a/Week_01/id_108/LeetCode_905_108.java b/Week_01/id_108/LeetCode_905_108.java new file mode 100644 index 00000000..0c56ff04 --- /dev/null +++ b/Week_01/id_108/LeetCode_905_108.java @@ -0,0 +1,51 @@ +/** + * @author zhangruihao.zhang + * @version v1.0.0 + * @since 2019/04/20 + */ +public class LeetCode_905_108 { + class Solution1 { + public int[] sortArrayByParity(int[] A) { + int left = 0; + int right = A.length - 1; + while(left < right){ + while( left< A.length && (A[left] & 1) == 0){ + left ++; + } + while( right>0 && (A[right] & 1) == 1){ + right --; + } + if(left < right) { + swap(A,left,right); + } + } + return A; + } + + private void swap(int[] A,int left,int right){ + int tmp = A[left]; + A[left] = A[right]; + A[right] = tmp; + } + } + + class Solution2 { + public int[] sortArrayByParity(int[] A) { + int[] even = new int[A.length]; + int[] odd = new int[A.length]; + int evenIndex = 0; + int oddIndex = 0; + for(int i=0 ;inext; + while(q != NULL && p->val == q->val) { + q = q->next; + } + + p->next = q; + p = p->next; + } + + return head; + } +}; diff --git a/Week_01/id_117/LeetCode_21_117.go b/Week_01/id_117/LeetCode_21_117.go new file mode 100644 index 00000000..9a0a7793 --- /dev/null +++ b/Week_01/id_117/LeetCode_21_117.go @@ -0,0 +1,32 @@ +package solution + +type ListNode struct { + Val int + Next *ListNode +} + +func mergeTwoLists(l1 *ListNode, l2 *ListNode) *ListNode { + res := &ListNode{} + cur := res + for l1 != nil || l2 != nil { + if l1 == nil { + cur.Next = l2 + l2 = nil + continue + } + if l2 == nil { + cur.Next = l1 + l1 = nil + continue + } + + if l1.Val > l2.Val { + cur.Next = l2 + cur, l2 = cur.Next, l2.Next + } else { + cur.Next = l1 + cur, l1 = cur.Next, l1.Next + } + } + return res.Next +} diff --git a/Week_01/id_117/LeetCode_21_117_test.go b/Week_01/id_117/LeetCode_21_117_test.go new file mode 100644 index 00000000..383dd227 --- /dev/null +++ b/Week_01/id_117/LeetCode_21_117_test.go @@ -0,0 +1,38 @@ +package solution + +import ( + "testing" +) + +func TestLeetCode_21_117(t *testing.T) { + node01 := &ListNode{Val: 1} + node02 := &ListNode{Val: 3} + node03 := &ListNode{Val: 3} + node01.Next = node02 + node02.Next = node03 + + node11 := &ListNode{Val: 1} + node12 := &ListNode{Val: 1} + node13 := &ListNode{Val: 2} + node11.Next = node12 + node12.Next = node13 + + newNode := mergeTwoLists(node01, node11) + temNode := newNode + rights := []int{1, 1, 1, 2, 3, 3} + news := []int{} + for temNode != nil { + news = append(news, temNode.Val) + temNode = temNode.Next + } + if len(rights) != len(news) { + t.Fatalf("False") + } + for i := 0; i < len(rights); i++ { + if news[i] != rights[i] { + t.Fatalf("False") + break + } + } + t.Log("True") +} diff --git a/Week_01/id_117/LeetCode_83_117.go b/Week_01/id_117/LeetCode_83_117.go new file mode 100644 index 00000000..5f1e6aae --- /dev/null +++ b/Week_01/id_117/LeetCode_83_117.go @@ -0,0 +1,30 @@ +package solution + +/** + * Definition for singly-linked list. + * type ListNode struct { + * Val int + * Next *ListNode + * } + */ +func deleteDuplicates(head *ListNode) *ListNode { + if head == nil { + return head + } + if head.Next == nil { + return head + } + p := head + q := p.Next + for q != nil { + if p.Val == q.Val { + p.Next = q.Next + q = p.Next + continue + } + p = p.Next + q = p.Next + + } + return head +} diff --git a/Week_01/id_117/LeetCode_83_117_test.go b/Week_01/id_117/LeetCode_83_117_test.go new file mode 100644 index 00000000..8350ad1f --- /dev/null +++ b/Week_01/id_117/LeetCode_83_117_test.go @@ -0,0 +1,31 @@ +package solution + +import "testing" + +func TestLeetCode_83_117(t *testing.T) { + node01 := &ListNode{Val: 1} + node02 := &ListNode{Val: 3} + node03 := &ListNode{Val: 3} + node01.Next = node02 + node02.Next = node03 + newNode := deleteDuplicates(node01) + temNode := newNode + + rights := []int{1, 3} + news := []int{} + + for temNode != nil { + news = append(news, temNode.Val) + temNode = temNode.Next + } + if len(rights) != len(news) { + t.Fatalf("False") + } + for i := 0; i < len(rights); i++ { + if news[i] != rights[i] { + t.Fatalf("False") + break + } + } + t.Log("True") +} diff --git a/Week_01/id_117/NOTE.md b/Week_01/id_117/NOTE.md index c684e62f..38a54937 100644 --- a/Week_01/id_117/NOTE.md +++ b/Week_01/id_117/NOTE.md @@ -1 +1,9 @@ -# 学习笔记 \ No newline at end of file +# 学习笔记 + +### 工作内容 +1.学习`java` +2.学习`elastic search` + +**说明:** +转眼周五了,先完成作业,等会儿练习. +我不会错过这个与大家一起的学习机会的. diff --git a/Week_01/id_118/NOTE.md b/Week_01/id_118/NOTE.md index c684e62f..2a4fdaf8 100644 --- a/Week_01/id_118/NOTE.md +++ b/Week_01/id_118/NOTE.md @@ -1 +1,58 @@ -# 学习笔记 \ No newline at end of file +# 本周学习重点 + +由于时间有限,本周学习重点放在 链表和数组 这两类题型上。 + +一些比较有收获的点是: +1. 同一类型的题目,可以从 easy 开始做,然后到 middle 最后再到 hard,层层递进,因为难题都是由简单题目演进而来的,由浅入深会比较容易接受, +2. 做题前,先对“已知信息”做收集,然后再看利用已有知识,如何达到题目要求。 +3. 解题思路可以靠画图辅助梳理,解法也可以在纸上走一遍进行推导,不要上来就写代码。 +4. 最后,同一题可以尝试用不同的方法去解决。 + + +# 链表题型总结 +本周截止写这篇总结时,做完的链表题目有: +- [leetcode.83.删除排序链表中的重复元素](https://leetcode-cn.com/problems/remove-duplicates-from-sorted-list/) +- [leetcode.21.合并两个有序链表](https://leetcode-cn.com/problems/merge-two-sorted-lists/) +- [leetcode.24.两两交换链表中的节点](https://leetcode-cn.com/problems/swap-nodes-in-pairs/) +- [leetcode.142.环形链表2](https://leetcode-cn.com/problems/linked-list-cycle-ii/) +- [leetcode.25.k个一组翻转链表](https://leetcode-cn.com/problems/reverse-nodes-in-k-group/) + +一些小总结: +- 链表题型,怎么都跑不了一些基本操作:插入节点(头、尾、中间),删除节点(头、尾、中间),相邻节点交换。所以,必须对这些操作熟悉的不能再熟悉。 +- 链表题型,比较常见的是: + - 删除指定条件的元素(eg:删除重复元素、删除倒数第k个节点、删除中间节点或a/b处的节点) + - 链表反转(eg:整体反转、两两反转、k个一组反转) + - 环的问题(eg:判断链表中是否有环、找到链表环的第一个节点) + - 两个链表的问题(eg:两个有序链表合并、求两个有序链表的公共部分) + - 。。。。。。 +- 链表问题的解法: + - 常规题,一般是辅助指针,加上常规的插入删除交换操作就可以搞定。 + - 部分题型需要结合哈希表。 + - 有一些题目需要用些小技巧,比如多次迭代、快慢指针等。 +- 写代码时需要注意的点: + - 注意不要丢节点,有一些操作的前后顺序很重要,一不小心就把后面的整条链给丢掉了。 + - 也不要造成环,链表拆解或合并,最容易出现这种情况,一定要在纸上把流程捋清晰了再写代码。 + - 有时候,加一个哨兵节点能够简化操作。 + + +# 数组题型总结 +本周截止到写这篇总结时,做完的链表题目有: +- [leetcode.905.按奇偶排序数组](https://leetcode-cn.com/problems/sort-array-by-parity/) +- [leetcpde.922.按奇偶排序数组2](https://leetcode-cn.com/problems/sort-array-by-parity-ii/) +- [leetcode.153.寻找旋转排序数组中的最小值](https://leetcode-cn.com/problems/find-minimum-in-rotated-sorted-array/submissions/) +- [leetcode.33.搜索旋转排序数组](https://leetcode-cn.com/problems/search-in-rotated-sorted-array/description/) +- [leetcode.704.二分查找](https://leetcode-cn.com/problems/binary-search/) + +一些小总结: +- 数组题型相比链表就比较杂了,我做过的题目也不是太多,以我浅薄的经验稍稍总结一下。 +- 数组的特点基本操作,一般是:数据移动交换或删除。不一般是:排序、二分、以及其他图算法等等。 +- 我目前做的这几道题,基本上都是排序和二分查找。几个关键点吧: + - 排序题目要么是冒泡、插入、归并等这些经典的算法题,要么是这些算法题的变种。其中以归并、快排的思路居多,也偶尔有一些插入排序的变形题。 + - 查找类题目,只要要求了 O(logn),基本上就二分没跑了,实现上可能能用递归解决。 +- 写代码时: + - 首先要注意数组越界问题。 + - 接下来是需要用到的索引指针的初始化的问题。 + - 以及,非常琐碎的边界点的问题,比如 是 > 还是 >=,是 left=middle 还是 left = middle+1。 + + + diff --git a/Week_01/id_118/leetcode_142_118.java b/Week_01/id_118/leetcode_142_118.java new file mode 100644 index 00000000..1cd153c5 --- /dev/null +++ b/Week_01/id_118/leetcode_142_118.java @@ -0,0 +1,54 @@ +/** + * https://leetcode-cn.com/problems/linked-list-cycle-ii/ + * + * Definition for singly-linked list. + * class ListNode { + * int val; + * ListNode next; + * ListNode(int x) { + * val = x; + * next = null; + * } + * } + */ +public class Solution { + public ListNode detectCycle(ListNode head) { + // 不允许修改给定的链表。也就是不能在数据节点做标记,也不能修改链表节点指向。 + // 第一种解法哈希表,第二种解法快慢指针。 + + // 1. 边界处理 + if(head == null || head.next == null){ + return null; + } + + // 2. 加哨兵节点 + ListNode guard = new ListNode(-1); + guard.next = head; + + // 3. 定义快慢指针 + ListNode fast = guard; + ListNode slow = guard; + + // 4. 遍历,检查是否有环。 + // - 要是没环的话,会直接抛出去 + // - 要是有环的话,则快慢指针一定会相遇,退出循环 + while(true){ + if(fast.next == null || fast.next.next==null){ + return null; + } + slow = slow.next; + fast = fast.next.next; + if(slow == fast){ + break; + } + } + + // 5. 查找环的位置 + slow = guard; + while(slow != fast){ + slow = slow.next; + fast= fast.next; + } + return slow; + } +} diff --git a/Week_01/id_118/leetcode_153_118.java b/Week_01/id_118/leetcode_153_118.java new file mode 100644 index 00000000..cbb792b4 --- /dev/null +++ b/Week_01/id_118/leetcode_153_118.java @@ -0,0 +1,33 @@ +/** + * https://leetcode-cn.com/problems/find-minimum-in-rotated-sorted-array/submissions/ + */ +class Solution { + public int findMin(int[] nums) { + // 从旋转节点分隔,左侧数据 > 右侧数据,所以找到这个旋转点就能找到最小值。 + + // 用二分的方式,进行递归 + // - nums[left] > nums[right] 则最小值一定在左边 + // - nums[left] < nums[right] 则最小值一定在右边 + // 递归终止条件为:left==right 或 left+1==right,最小值为 nums[right]。 + + // PS:有一个点要特别需要注意的是,如果本身已经有序了(第一个点<最后一个点),就不需要这么找了,第一个就是最小值。 + + if(nums[0] < nums[nums.length-1]){ + return nums[0]; + } + return findMin(nums,0,nums.length-1); + } + + int findMin(int[] nums,int left,int right){ + // 找到反转位置 + if(left == right || left+1==right){ + return nums[right]; + } + int middle = left+(right-left)/2; + if(nums[left] > nums[middle]){ + return findMin(nums,left,middle); + }else{ + return findMin(nums,middle,right); + } + } +} diff --git a/Week_01/id_118/leetcode_21_118.java b/Week_01/id_118/leetcode_21_118.java new file mode 100644 index 00000000..223f3c30 --- /dev/null +++ b/Week_01/id_118/leetcode_21_118.java @@ -0,0 +1,53 @@ + +/** + * + * https://leetcode-cn.com/problems/merge-two-sorted-lists/submissions/ + * + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode(int x) { val = x; } + * } + */ +class Solution { + public ListNode mergeTwoLists(ListNode l1, ListNode l2) { + + // 1. 边界处理:两个都为null或任意一个为null + if(l1==null || l2==null ){ + return l1 == null ? l2 : l1; + } + + // 2. 初始化新链表中的节点。 + // - 为了简化处理,初始化一个头结点作为哨兵节点,值为0。 + // - 再初始化一个临时指针,指向头结点,从头开始往链表上挂节点。 + ListNode head = new ListNode(0); + ListNode current = head; + + // 3. 同时遍历两个链表,哪个头结点值最小,则把哪个节点的头拆下来 + // - 注意,拆头结点的时候,千万别把指针拆丢了 + while(l1!=null && l2!=null){ + if(l1.val<=l2.val){ + current.next = l1; + l1=l1.next; + }else{ + current.next = l2; + l2=l2.next; + } + current=current.next; + current.next = null; + } + + // 4. 边界处理:可能某一个指针还没走完,直接无脑追加上就好了 + if(l1!=null){ + current.next = l1; + } + if(l2!=null){ + current.next = l2; + } + + // 5. 最后,返回 head.next,因为head节点数据无意义 + return head.next; + + } +} diff --git a/Week_01/id_118/leetcode_24_118.java b/Week_01/id_118/leetcode_24_118.java new file mode 100644 index 00000000..424d6148 --- /dev/null +++ b/Week_01/id_118/leetcode_24_118.java @@ -0,0 +1,52 @@ +/** + * https://leetcode-cn.com/problems/swap-nodes-in-pairs/ + * + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode(int x) { val = x; } + * } + */ +class Solution { + public ListNode swapPairs(ListNode head) { + + // 1. 边界:空链表或只有一个节点 + if(head==null || head.next == null){ + return head; + } + + // 2. 为了方便处理,需要加一个哨兵节点,指向 head + ListNode guard = new ListNode(0); + guard.next = head; + + // 3. 然后,两个节点的交换需要涉及到其前后节点,加起来共四个节点,按顺序分别将他们定义为: + // start_left,要交换两个节点中起点的前一个节点。初始为 guard + // start,要交换的起点。初始为 head + // end,要交换的终点。初始为 head.next + // end_right,要交换的两个节点中终点的后一个节点。初始为 head.next.next。这个节点有可能为空 + ListNode start_left = guard; + ListNode start = head; + ListNode end = head.next; + ListNode end_right = head.next.next; + + // 4. 开始做节点交换和指针移动,end==null时停止 + while(end!=null){ + // 先交换 + start_left.next = end; + start.next = end_right; + end.next = start; + // 后移动。注意判断接下来是否还有两个非空节点 + if(end_right == null || end_right.next == null){ + break; + } + start_left = start; + start = start_left.next; + end = start.next; + end_right = end.next; + } + + // 5. 最后返回 guard.next。注意,这里不要返回 head,因为head 已经被交换到第二个节点了。 + return guard.next; + } +} diff --git a/Week_01/id_118/leetcode_25_118.java b/Week_01/id_118/leetcode_25_118.java new file mode 100644 index 00000000..55f14573 --- /dev/null +++ b/Week_01/id_118/leetcode_25_118.java @@ -0,0 +1,79 @@ +/** + * https://leetcode-cn.com/problems/reverse-nodes-in-k-group/ + * + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode(int x) { val = x; } + * } + */ +class Solution { + public ListNode reverseKGroup(ListNode head, int k) { + + // 1. 边界值处理:空指针、一个节点、k小于等于1 + if(head==null || head.next==null || k<=1){ + return head; + } + + // 2. 加哨兵节点 + ListNode guard = new ListNode(0); + guard.next = head; + + // 3. 左侧已翻转完链表的尾节点,并将其指向 null,避免产生环 + ListNode left = guard; + left.next = null; + + // 4. head 不为 null,则持续翻转 + while(head!=null){ + + // 判断剩下的部分是否还有 k 个节点能翻转 + if(!hasEnoughNode(head,k)){ + break; + } + + // 把头结点提拉出来,作为翻转部分的第一个节点 + ListNode new_tail = head;// 新翻转链表的尾节点 + ListNode new_head = head;// 新翻转链表的头结点 + head = head.next; + new_tail.next = null;// 这是为了避免误操作搞出环来 + + // 然后再找k-1个节点出来,插到链表头 + int count = k-1; + while(count!=0){ + ListNode tmp = head; + head = head.next; + tmp.next = new_head; + new_head = tmp; + count--; + } + + // 左边的链表,和新翻转的链表串起来 + left.next = new_head; + + // 移动尾巴 + left = new_tail; + } + + // 5.最后再把没反转的部分给链上 + left.next = head; + + // 6. 返回 + return guard.next; + } + + + // 判断后面是否还有足够的节点可以反转。 + boolean hasEnoughNode(ListNode head,int k){ + ListNode tmp = head; + while(k!=0){ + if(tmp == null){ + return false; + } + tmp=tmp.next; + k--; + } + return true; + } + +} diff --git a/Week_01/id_118/leetcode_33_118.java b/Week_01/id_118/leetcode_33_118.java new file mode 100644 index 00000000..311e38b2 --- /dev/null +++ b/Week_01/id_118/leetcode_33_118.java @@ -0,0 +1,44 @@ +/** + * https://leetcode-cn.com/problems/search-in-rotated-sorted-array/ + */ +class Solution { + public int search(int[] A, int target) { + // 非递归 + + // 边界处理 + if(A.length<1){ + return -1; + } + + // 定义左右索引 + int left =0; + int right = A.length-1; + + // 折半搜索。需要特别注意,用 >= 还是 >,用 left=mid 还是 left=mid+1。十分重要!!! + while(left <= right){ + int mid = (left+right)/2; + + if(A[mid] == target){ + return mid; + } + + if(A[mid] < A[right]){ + if(target>A[mid] && target<=A[right]){ + left=mid+1; + } + else{ + right = mid-1; + } + }else{ + if(target>=A[left] && target right){ + return -1; + } + int middle = (right+left)/2; + if(target>nums[middle]){ + return search(nums,target,middle+1,right); + }else if(target + left.next = null; + return head; + } +} diff --git a/Week_01/id_118/leetcode_905_118.java b/Week_01/id_118/leetcode_905_118.java new file mode 100644 index 00000000..8421cd96 --- /dev/null +++ b/Week_01/id_118/leetcode_905_118.java @@ -0,0 +1,48 @@ +/** + * https://leetcode-cn.com/problems/sort-array-by-parity/submissions/ + */ + +class Solution { + public int[] sortArrayByParity(int[] A) { + + // 1. 边界处理,长度 <=1 什么都不做 + if(A.length<=1){ + return A; + } + + // 2. 定义前后索引 + int left = 0; + int right = A.length-1; + + // 3. 移动元素 + while(left(); + char[] chars = s.toCharArray(); + for (int i = 0;i < chars.length;i ++) { + char c = chars[i]; + if(c == '(' || c == '[' || c == '{'){ + stack.push(c); + continue; + } + if(c == ')' || c == ']' || c == '}'){ + if(stack.isEmpty()){ + return false; + } + char pop = (Character)stack.pop(); + Character right = dic.get(pop); + if(right == c ){ + if(stack.isEmpty() && i == chars.length -1){ + return true; + } + continue; + } + return false; + } + } + return false; + } +} \ No newline at end of file diff --git a/Week_01/id_121/LeetCode_21_121.java b/Week_01/id_121/LeetCode_21_121.java new file mode 100644 index 00000000..809f5a82 --- /dev/null +++ b/Week_01/id_121/LeetCode_21_121.java @@ -0,0 +1,31 @@ +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode(int x) { val = x; } + * } + */ +class Solution { + public ListNode mergeTwoLists(ListNode l1, ListNode l2) { + ListNode head = new ListNode(0); + ListNode pos = head; + while(l1 != null && l2 != null){ + if(l1.val <= l2.val){ + pos.next = l1; + l1 = l1.next; + }else{ + pos.next = l2; + l2 = l2.next; + } + pos = pos.next; + } + if(l1 == null && l2 != null){ + pos.next = l2; + }else if(l1 != null && l2 == null){ + pos.next = l1; + } + return head.next; + + } +} \ No newline at end of file diff --git a/Week_01/id_121/LeetCode_24_121.java b/Week_01/id_121/LeetCode_24_121.java new file mode 100644 index 00000000..8954e690 --- /dev/null +++ b/Week_01/id_121/LeetCode_24_121.java @@ -0,0 +1,46 @@ +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode(int x) { val = x; } + * } + */ +class Solution { + public ListNode swapPairs(ListNode head) { + if(head == null ){ + return null; + } + if(head.next == null){ + return head; + } + + ListNode preNode = head; + ListNode curNode = head.next; + ListNode retNode = curNode; + ListNode newPreNode = null; + while(preNode != null && curNode != null){ + removeCurNode(preNode,curNode); + insertBeforeCurNode(newPreNode,preNode,curNode); + preNode = curNode.next.next; + newPreNode = curNode.next; + if(preNode != null){ + curNode = preNode.next; + } + } + return retNode; + } + + private void removeCurNode(ListNode preNode,ListNode curNode){ + if(preNode != null){ + preNode.next = curNode.next; + } + curNode.next = null; + } + private void insertBeforeCurNode(ListNode preNode,ListNode curNode,ListNode node){ + node.next = curNode; + if(preNode != null){ + preNode.next = node; + } + } +} \ No newline at end of file diff --git a/Week_01/id_121/LeetCode_83_121.java b/Week_01/id_121/LeetCode_83_121.java new file mode 100644 index 00000000..651de673 --- /dev/null +++ b/Week_01/id_121/LeetCode_83_121.java @@ -0,0 +1,21 @@ +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode(int x) { val = x; } + * } + */ +class Solution { + public ListNode deleteDuplicates(ListNode head) { + ListNode cur = head; + while(cur != null && cur.next != null){ + if(cur.val == cur.next.val){ + cur.next = cur.next.next; + }else{ + cur = cur.next; + } + } + return head; + } +} \ No newline at end of file diff --git a/Week_01/id_121/LeetCode_905_121.java b/Week_01/id_121/LeetCode_905_121.java new file mode 100644 index 00000000..27a21878 --- /dev/null +++ b/Week_01/id_121/LeetCode_905_121.java @@ -0,0 +1,37 @@ +class Solution { + public int[] sortArrayByParity(int[] A) { + if(A == null || A.length < 1 || A.length > 5000){ + return null; + } + int head = 0; + int tail = A.length - 1; + while(head >=0 && tail>= 0 && head < A.length && tail < A.length && head < tail){ + if(!isOdd(A[head]) && isOdd(A[tail])){ + head ++; + tail --; + }else if(isOdd(A[head]) && !isOdd(A[tail])){ + swap(A,head,tail); + head ++; + tail --; + }else if(isOdd(A[head]) && isOdd(A[tail])){ + tail --; + }else if(!isOdd(A[head]) && !isOdd(A[tail])){ + head ++; + } + + } + return A; + } + public void swap(int[] arr,int head,int tail){ + int tmp = arr[head]; + arr[head] = arr[tail]; + arr[tail] = tmp; + } + public boolean isOdd(int a){ + if(a%2 == 1){ //是奇数 + return true; + } + return false; + } + +} \ No newline at end of file diff --git a/Week_01/id_121/LeetCode_922_121.java b/Week_01/id_121/LeetCode_922_121.java new file mode 100644 index 00000000..0bbdc9c1 --- /dev/null +++ b/Week_01/id_121/LeetCode_922_121.java @@ -0,0 +1,36 @@ +class Solution { + public int[] sortArrayByParityII(int[] A) { + if(A.length < 2 || A.length > 20000 || A.length % 2 != 0){ + return null; + } + + int even = 0; + int odd = 1; + while(even < A.length && odd < A.length){ + if(!isOdd(A[even]) && isOdd(A[odd])){ + odd = odd + 2; + even = even + 2; + }else if(isOdd(A[even]) && !isOdd(A[odd])){ + swap(A,even,odd); + odd = odd + 2; + even = even + 2; + }else if(isOdd(A[odd]) && isOdd(A[even])){ + odd = odd + 2; + }else if(!isOdd(A[odd]) && !isOdd(A[even])){ + even = even + 2; + } + } + return A; + } + public void swap(int[] arr,int head,int tail){ + int tmp = arr[head]; + arr[head] = arr[tail]; + arr[tail] = tmp; + } + public boolean isOdd(int a){ + if(a%2 == 1){ //是奇数 + return true; + } + return false; + } +} \ No newline at end of file diff --git a/Week_01/id_121/NOTE.md b/Week_01/id_121/NOTE.md index c684e62f..19f0c1e0 100644 --- a/Week_01/id_121/NOTE.md +++ b/Week_01/id_121/NOTE.md @@ -1 +1,6 @@ -# 学习笔记 \ No newline at end of file +# 学习笔记 + +## week01 + - 做题之前先看清楚题目条件,并且要充分利用已知条件 + - 写完代码要代入几个边界条件的case 去测试一下 + - 有条件一定要画图,帮助自己思考 \ No newline at end of file diff --git a/Week_01/id_122/LeetCode_142_122.py b/Week_01/id_122/LeetCode_142_122.py new file mode 100644 index 00000000..53a25973 --- /dev/null +++ b/Week_01/id_122/LeetCode_142_122.py @@ -0,0 +1,26 @@ +# Definition for singly-linked list. +# class ListNode(object): +# def __init__(self, x): +# self.val = x +# self.next = None + +class Solution(object): + def detectCycle(self, head): + """ + :type head: ListNode + :rtype: ListNode + """ + if head is None or head.next is None or head.next.next is None: + return + p1 = head.next + p2 = head.next.next + while(p2 is not None and p2.next is not None and p2.next.next is not None): + p1 = p1.next + p2 = p2.next.next + if p1 is p2: + p1 = head + while p1 is not p2: + p1 = p1.next + p2 = p2.next + return p1 + return \ No newline at end of file diff --git a/Week_01/id_122/LeetCode_21_122.php b/Week_01/id_122/LeetCode_21_122.php new file mode 100644 index 00000000..eab8ba91 --- /dev/null +++ b/Week_01/id_122/LeetCode_21_122.php @@ -0,0 +1,75 @@ +val = $val; } + * } + */ + +class ListNode { + public $val = 0; + public $next = null; + function __construct($val) { $this->val = $val; } +} + +class Solution { + + /** + * @param ListNode $l1 + * @param ListNode $l2 + * @return ListNode + */ + function mergeTwoLists($l1, $l2) { + if ($l1 == null) { + return $l2; + } + + if ($l2 == null) { + return $l1; + } + + $first = $l1; + $second = $l2; + + if ($first->val <= $second->val) { + $head = $first; + $first = $first->next; + } else { + $head = $second; + $second = $second->next; + } + + $now = $head; + + while (true) { + if ($first == null) { + $now->next = $second; + break; + } + if ($second == null) { + $now->next = $first; + break; + } + + if ($first->val <= $second->val) { + $now->next = $first; + $first = $first->next; + $now = $now->next; + continue; + } + $now->next = $second; + $second = $second->next; + $now = $now->next; + } + return $head; + } +} \ No newline at end of file diff --git a/Week_01/id_122/LeetCode_24_122.php b/Week_01/id_122/LeetCode_24_122.php new file mode 100644 index 00000000..85c22dfd --- /dev/null +++ b/Week_01/id_122/LeetCode_24_122.php @@ -0,0 +1,49 @@ +val = $val; } + * } + */ +class ListNode { + public $val = 0; + public $next = null; + function __construct($val) { $this->val = $val; } +} + +class Solution { + + /** + * @param ListNode $head + * @return ListNode + */ + function swapPairs($head) { + + //没有元素,或者只有一个元素 + if ($head == null || $head->next == null) { + return $head; + } + $shaoBing = new ListNode(null); + $shaoBing->next = $head->next; + + //到这里至少链表中至少有两个元素 + $prev = $head; + $prior = $prev->next; + $next = $prior->next; + + while ($next && $next->next) { + $prev->next = $next->next; + $prior->next = $prev; + $prev = $next; + $prior = $next->next; + $next = $prior->next; + } + + //最后交换末尾两个元素, 针对单数个链表元素做处理 + $prev->next = $next ? $next : null; + $prior->next = $prev; + return $shaoBing->next; + } +} diff --git a/Week_01/id_122/LeetCode_687_122.php b/Week_01/id_122/LeetCode_687_122.php new file mode 100644 index 00000000..9b38344b --- /dev/null +++ b/Week_01/id_122/LeetCode_687_122.php @@ -0,0 +1,52 @@ +val = $value; } + * } + */ +class TreeNode { + public $val = null; + public $left = null; + public $right = null; + function __construct($value) { $this->val = $value; } +} + +class Solution { + private $max = 0; + + /** + * @param TreeNode $root + * @return Integer + */ + function longestUnivaluePath($root) { + if (!$root) { + return 0; + } + $this->maxP($root, $root->val); + return $this->max; + } + + function maxP($root, $val) { + if (!$root) { + return 0; + } + $left = $this->maxP($root->left, $root->left->val); + $right = $this->maxP($root->right, $root->right->val); + $this->max = max($this->max, $left + $right); + if ($root->val == $val) { + return max($left, $right) + 1; + } + return 0; + } +} \ No newline at end of file diff --git a/Week_01/id_122/LeetCode_83_122.php b/Week_01/id_122/LeetCode_83_122.php new file mode 100644 index 00000000..c1394ffe --- /dev/null +++ b/Week_01/id_122/LeetCode_83_122.php @@ -0,0 +1,46 @@ +val = $val; } + * } + */ + +class ListNode { + public $val = 0; + public $next = null; + function __construct($val) { $this->val = $val; } +} + +class Solution { + + /** + * @param ListNode $head + * @return ListNode + */ + function deleteDuplicates($head) { + if ($head == null) { + return $head; + } + $prior = $head; + while ($prior->next) { + $next = $prior->next; + if ($prior->val == $next->val) { + $prior->next = $next->next; + $next->next = null; + continue; + } + $prior = $prior->next; + } + return $head; + } +} \ No newline at end of file diff --git a/Week_01/id_123/LeetCode_20_123.go b/Week_01/id_123/LeetCode_20_123.go new file mode 100644 index 00000000..2ad4036a --- /dev/null +++ b/Week_01/id_123/LeetCode_20_123.go @@ -0,0 +1,73 @@ +package id_123 + +import "github.com/pkg/errors" + +//给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。 +// +//有效字符串需满足: +// +//左括号必须用相同类型的右括号闭合。 +//左括号必须以正确的顺序闭合。 + +type Stack struct { + data []byte + count int + n int +} + +func (s *Stack) init(n int) { + s.data = make([]byte, n) + s.n = n +} + +func (s *Stack) push(c byte) error { + if s.count == s.n { + return errors.New("Stack full!") + } + + s.count++ + s.data[s.count-1] = c + return nil +} + +func (s *Stack) pop() (byte, error) { + if s.count == 0 { + return 0, errors.New("Stack empty!") + } + + value := s.data[s.count-1] + s.count-- + return value, nil +} + +func isValid(s string) bool { + stack := new(Stack) + stack.init(len(s)) + + for _, c := range s { + if c == '{' || c == '[' || c == '(' { + stack.push(byte(c)) + } else { + if stack.count == 0 { + return false + } else { + v, _ := stack.pop() + if v == '{' && c == '}' { + continue + } else if v == '[' && c == ']' { + continue + } else if v == '(' && c == ')' { + continue + } else { + return false + } + } + } + } + + if stack.count == 0 { + return true + } else { + return false + } +} diff --git a/Week_01/id_123/LeetCode_20_123_test.go b/Week_01/id_123/LeetCode_20_123_test.go new file mode 100644 index 00000000..b1a8987d --- /dev/null +++ b/Week_01/id_123/LeetCode_20_123_test.go @@ -0,0 +1,57 @@ +package id_123 + +import "testing" + +func Test_isValid(t *testing.T) { + type args struct { + s string + } + tests := []struct { + name string + args args + want bool + }{ + { + name: "test1", + args: args{ + s: "[[[]]]", + }, + want: true, + }, + { + name: "test2", + args: args{ + s: "[[()]]", + }, + want: true, + }, + { + name: "test3", + args: args{ + s: "[[(]]", + }, + want: false, + }, + { + name: "test4", + args: args{ + s: "[[{}]]", + }, + want: true, + }, + { + name: "test5", + args: args{ + s: "(]", + }, + want: false, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := isValid(tt.args.s); got != tt.want { + t.Errorf("isValid() = %v, want %v", got, tt.want) + } + }) + } +} diff --git a/Week_01/id_123/LeetCode_242_123.go b/Week_01/id_123/LeetCode_242_123.go new file mode 100644 index 00000000..002b4bff --- /dev/null +++ b/Week_01/id_123/LeetCode_242_123.go @@ -0,0 +1,15 @@ +package id_123 + +import "sort" + +func sortString(s string) string { + charSlice := []rune(s) + sort.Slice(charSlice, func(i, j int) bool { + return charSlice[i] < charSlice[j] + }) + return string(charSlice) +} + +func isAnagram(s string, t string) bool { + return sortString(s) == sortString(t) +} diff --git a/Week_01/id_123/LeetCode_242_123_test.go b/Week_01/id_123/LeetCode_242_123_test.go new file mode 100644 index 00000000..a697efe2 --- /dev/null +++ b/Week_01/id_123/LeetCode_242_123_test.go @@ -0,0 +1,62 @@ +package id_123 + +import ( + "testing" +) + +func Test_sortString(t *testing.T) { + s := "国中" + t.Log(sortString(s)) +} + +func Test_isAnagram(t *testing.T) { + type args struct { + s string + t string + } + tests := []struct { + name string + args args + want bool + }{ + { + name: "test1", + args: args{ + s: "abcd", + t: "abcd", + }, + want: true, + }, + { + name: "test2", + args: args{ + s: "abdc", + t: "abcd", + }, + want: true, + }, + { + name: "test3", + args: args{ + s: "abdc", + t: "abcc", + }, + want: false, + }, + { + name: "test4", + args: args{ + s: "中国", + t: "国中", + }, + want: true, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := isAnagram(tt.args.s, tt.args.t); got != tt.want { + t.Errorf("isAnagram() = %v, want %v", got, tt.want) + } + }) + } +} diff --git a/Week_01/id_123/LeetCode_441_123.go b/Week_01/id_123/LeetCode_441_123.go new file mode 100644 index 00000000..6bad2d18 --- /dev/null +++ b/Week_01/id_123/LeetCode_441_123.go @@ -0,0 +1,21 @@ +package id_123 + +func arrangeCoins(n int) int { + if n == 0 { + return 0 + } + var low = 1 + var high = n/2 + 1 + for low <= high { + var mid = low + (high-low)>>1 + var sum = (mid + 1) * mid / 2 + if sum > n { + high = mid - 1 + } else if sum < n { + low = mid + 1 + } else if sum == n { + return mid + } + } + return low - 1 +} diff --git a/Week_01/id_123/LeetCode_441_123_test.go b/Week_01/id_123/LeetCode_441_123_test.go new file mode 100644 index 00000000..c0ac63f1 --- /dev/null +++ b/Week_01/id_123/LeetCode_441_123_test.go @@ -0,0 +1,50 @@ +package id_123 + +import "testing" + +func Test_arrangeCoins(t *testing.T) { + type args struct { + n int + } + tests := []struct { + name string + args args + want int + }{ + { + name: "test1", + args: args{ + n: 3, + }, + want: 2, + }, + { + name: "test2", + args: args{ + n: 5, + }, + want: 2, + }, + { + name: "test3", + args: args{ + n: 5, + }, + want: 2, + }, + { + name: "test4", + args: args{ + n: 6, + }, + want: 3, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := arrangeCoins(tt.args.n); got != tt.want { + t.Errorf("arrangeCoins() = %v, want %v", got, tt.want) + } + }) + } +} diff --git a/Week_01/id_123/LeetCode_83_123.go b/Week_01/id_123/LeetCode_83_123.go new file mode 100644 index 00000000..58680aba --- /dev/null +++ b/Week_01/id_123/LeetCode_83_123.go @@ -0,0 +1,77 @@ +package id_123 + +import "fmt" + +//Definition for singly-linked list. +type ListNode struct { + Val int + Next *ListNode +} + +func addNodeToHead(head *ListNode, val int) *ListNode { + if head == nil { + return nil + } + + node := ListNode{ + Val: val, + Next: nil, + } + node.Next = head.Next + head.Next = &node + + return head +} + +func addNodeToTail(head *ListNode, val int) *ListNode { + if head == nil { + return nil + } + + p := head + for p.Next != nil { + p = p.Next + } + + node := ListNode{ + Val: val, + Next: nil, + } + + p.Next = &node + + return head +} + +func printAllNode(head *ListNode) { + if head == nil { + return + } + + p := head.Next + valArray := make([]int, 0) + for p != nil { + valArray = append(valArray, p.Val) + p = p.Next + } + + fmt.Printf("%v\n", valArray) +} + +func deleteDuplicates(head *ListNode) *ListNode { + existValMap := make(map[int]bool, 0) + + p := head + var prev *ListNode + for p != nil { + if _, ok := existValMap[p.Val]; ok { + prev.Next = p.Next + } else { + existValMap[p.Val] = true + prev = p + } + p = p.Next + } + + return head +} diff --git a/Week_01/id_123/LeetCode_83_123_test.go b/Week_01/id_123/LeetCode_83_123_test.go new file mode 100644 index 00000000..71687907 --- /dev/null +++ b/Week_01/id_123/LeetCode_83_123_test.go @@ -0,0 +1,75 @@ +package id_123 + +import ( + "testing" +) + +func Test_deleteDuplicates(t *testing.T) { + + head := ListNode{ + Val: 0, + Next: nil, + } + + addNodeToTail(&head, 1) + addNodeToTail(&head, 1) + addNodeToTail(&head, 2) + addNodeToTail(&head, 2) + addNodeToTail(&head, 3) + addNodeToTail(&head, 4) + println("原始数据:") + printAllNode(&head) + + deleteDuplicates(head.Next) + println("去重后数据:") + printAllNode(&head) +} + +func Benchmark_deleteDuplicates(b *testing.B) { + for i := 0; i < b.N; i++ { + head := ListNode{ + Val: 0, + Next: nil, + } + + addNodeToTail(&head, 1) + addNodeToTail(&head, 1) + addNodeToTail(&head, 2) + addNodeToTail(&head, 2) + addNodeToTail(&head, 3) + addNodeToTail(&head, 4) + //println("原始数据:") + //printAllNode(&head) + + deleteDuplicates(head.Next) + //println("去重后数据:") + //printAllNode(&head) + } +} + +func Test_addNodeToTail(t *testing.T) { + head := ListNode{ + Val: 0, + Next: nil, + } + + addNodeToTail(&head, 1) + addNodeToTail(&head, 1) + addNodeToTail(&head, 2) + addNodeToTail(&head, 3) + addNodeToTail(&head, 4) + printAllNode(&head) +} + +func Test_addNodeToHead(t *testing.T) { + head := ListNode{ + Val: 0, + Next: nil, + } + + addNodeToHead(&head, 1) + addNodeToHead(&head, 2) + addNodeToHead(&head, 3) + addNodeToHead(&head, 4) + printAllNode(&head) +} diff --git a/Week_01/id_123/LeetCode_905_123.go b/Week_01/id_123/LeetCode_905_123.go new file mode 100644 index 00000000..7840b75b --- /dev/null +++ b/Week_01/id_123/LeetCode_905_123.go @@ -0,0 +1,14 @@ +package id_123 + +func sortArrayByParity(A []int) []int { + evenArr := make([]int, 0) + oddArr := make([]int, 0) + for _, v := range A { + if v%2 == 0 { + evenArr = append(evenArr, v) + } else { + oddArr = append(oddArr, v) + } + } + return append(evenArr, oddArr...) +} diff --git a/Week_01/id_123/LeetCode_905_123_test.go b/Week_01/id_123/LeetCode_905_123_test.go new file mode 100644 index 00000000..4692adab --- /dev/null +++ b/Week_01/id_123/LeetCode_905_123_test.go @@ -0,0 +1,13 @@ +package id_123 + +import ( + "fmt" + "testing" +) + +func Test_sortArrayByParity(t *testing.T) { + A := []int{3, 1, 2, 4, 8, 5, 7, 10, 12} + fmt.Printf("sort before: %v\n", A) + B := sortArrayByParity(A) + fmt.Printf("sort after: %v\n", B) +} diff --git a/Week_01/id_123/LeetCode_922_123.go b/Week_01/id_123/LeetCode_922_123.go new file mode 100644 index 00000000..c64df1e8 --- /dev/null +++ b/Week_01/id_123/LeetCode_922_123.go @@ -0,0 +1,22 @@ +package id_123 + +func sortArrayByParityII(A []int) []int { + newArr := make([]int, 0, 20000) + + evenArr := make([]int, 0) + oddArr := make([]int, 0) + for _, v := range A { + if v%2 == 0 { + evenArr = append(evenArr, v) + } else { + oddArr = append(oddArr, v) + } + } + + for i := 0; i < len(evenArr); i++ { + newArr = append(newArr, evenArr[i]) + newArr = append(newArr, oddArr[i]) + } + + return newArr +} diff --git a/Week_01/id_123/LeetCode_922_123_test.go b/Week_01/id_123/LeetCode_922_123_test.go new file mode 100644 index 00000000..fe1674f9 --- /dev/null +++ b/Week_01/id_123/LeetCode_922_123_test.go @@ -0,0 +1,13 @@ +package id_123 + +import ( + "log" + "testing" +) + +func Test_sortArrayByParityII(t *testing.T) { + A := []int{4, 2, 5, 7} + log.Printf("sort before: %v", A) + B := sortArrayByParityII(A) + log.Printf("sort after: %v", B) +} diff --git a/Week_01/id_124/LeetCode_142_124.java b/Week_01/id_124/LeetCode_142_124.java new file mode 100644 index 00000000..98acb73c --- /dev/null +++ b/Week_01/id_124/LeetCode_142_124.java @@ -0,0 +1,50 @@ +import common.ListNode; + +import java.util.HashSet; +import java.util.Set; + +public class DetectCycle { + public ListNode detectCycle(ListNode head) { + if (head == null || head.next == null) { + return null; + } + ListNode fast = head; + ListNode slow = head; + while (fast != null) { + if (fast.next == null) { + return null; + } + fast = fast.next.next; + slow = slow.next; + if (fast == slow) { + fast = head; + while (fast != slow) { + fast = fast.next; + slow = slow.next; + } + break; + } + + } + + return fast; + } + + public ListNode detectCycleByMap(ListNode head) { + Set set = new HashSet<>(); + while (head != null) { + if (set.contains(head)) { + return head; + } else { + set.add(head); + } + head = head.next; + } + return null; + } + + + public static void main(String[] args) { + + } +} diff --git a/Week_01/id_124/LeetCode_20_124.java b/Week_01/id_124/LeetCode_20_124.java new file mode 100644 index 00000000..5c54b02b --- /dev/null +++ b/Week_01/id_124/LeetCode_20_124.java @@ -0,0 +1,35 @@ +import java.util.HashMap; +import java.util.Map; +import java.util.Stack; + +public class IsValidBrackets { + + public boolean isValid(String s) { + Stack stack = new Stack<>(); + Map brackets = new HashMap<>(); + brackets.put(')', '('); + brackets.put(']', '['); + brackets.put('}', '{'); + char[] cArr = s.toCharArray(); + for (char c : cArr) { + if (stack.isEmpty()){ + stack.push(c); + continue; + } + char topc = stack.peek(); + if (brackets.containsKey(c) && topc == brackets.get(c)) { + stack.pop(); + }else { + stack.push(c); + } + + } + return stack.isEmpty(); + } + + public static void main(String[] args) { + IsValidBrackets brackets = new IsValidBrackets(); + System.out.println(brackets.isValid("()]")); + + } +} diff --git a/Week_01/id_124/LeetCode_242_124.java b/Week_01/id_124/LeetCode_242_124.java new file mode 100644 index 00000000..a6611027 --- /dev/null +++ b/Week_01/id_124/LeetCode_242_124.java @@ -0,0 +1,30 @@ +import java.util.HashMap; +import java.util.Map; + +public class IsAnagram { + + public boolean isAnagramByMap(String s, String t) { + if(s.length() != t.length()){ + return false; + } + Map cMap = new HashMap<>(); + for (Character c : s.toCharArray()) { + Integer cnt = cMap.getOrDefault(c, 0); + cMap.put(c, cnt + 1); + } + for (Character c : t.toCharArray()) { + if (!cMap.containsKey(c)) { + return false; + } + Integer cnt = cMap.getOrDefault(c, 0); + cMap.put(c, cnt - 1); + } + for (Integer cnt : cMap.values()) { + if (cnt > 0) { + return false; + } + } + return true; + } + +} diff --git a/Week_01/id_124/LeetCode_24_124.java b/Week_01/id_124/LeetCode_24_124.java new file mode 100644 index 00000000..b797bb34 --- /dev/null +++ b/Week_01/id_124/LeetCode_24_124.java @@ -0,0 +1,35 @@ +import common.ListNode; + +public class SwapPairs { + + public ListNode swapPairs(ListNode head) { + if (head == null || head.next == null) { + return head; + } + ListNode dummy = new ListNode(-1); + dummy.next = head; + ListNode cur = dummy; + while (cur.next != null && cur.next.next != null) { + ListNode next = cur.next; + ListNode nextNext = cur.next.next; + next.next = nextNext.next; + nextNext.next = next; + cur.next = nextNext; + cur = nextNext.next; + } + return dummy.next; + } + + public static void main(String[] args) { + ListNode node1 = new ListNode(1); + ListNode node2 = new ListNode(2); + ListNode node3 = new ListNode(3); + ListNode node4 = new ListNode(4); + node1.next = node2; + node2.next = node3; + node3.next = node4; + SwapPairs swapPairs = new SwapPairs(); + swapPairs.swapPairs(node1); + } + +} diff --git a/Week_01/id_124/LeetCode_83_124.java b/Week_01/id_124/LeetCode_83_124.java new file mode 100644 index 00000000..f9120b29 --- /dev/null +++ b/Week_01/id_124/LeetCode_83_124.java @@ -0,0 +1,22 @@ +import common.ListNode; + +public class DeleteDuplicates { + + public ListNode deleteDuplicates(ListNode head) { + ListNode dummy = new ListNode(-1); + dummy.next = head; + ListNode node = head; + while (node != null) { + if (node.next != null && node.val == node.next.val) { + node.next = node.next.next; + }else { + node = node.next; + } + } + return dummy.next; + } + + public static void main(String[] args) { + + } +} diff --git a/Week_01/id_124/LeetCode_905_124.java b/Week_01/id_124/LeetCode_905_124.java new file mode 100644 index 00000000..2c2b6109 --- /dev/null +++ b/Week_01/id_124/LeetCode_905_124.java @@ -0,0 +1,49 @@ +public class SortArrayByParity { + + public int[] sortArrayByParity(int[] A) { + int length = A.length; + for (int i = 0, j = length - 1; i < j; ) { + if (A[i] % 2 != 0 && A[j] % 2 != 1) { + int temp = A[j]; + A[j] = A[i]; + A[i] = temp; + i++; + j--; + } else if (A[i] % 2 == 0) { + i++; + } else if (A[j] % 2 == 1) { + j--; + } + } + return A; + + } + + private boolean isOdd(int num) { + return num % 2 == 0; + } + + public int[] sortArrayByParityII(int[] A) { + int length = A.length; + if (length < 2) { + return A; + } + for (int i = 0, j = 1; i < length && j < length; ) { + if (isOdd(i) && isOdd(A[i])) { + i += 2; + }else if (!isOdd(j) && !isOdd(A[j])) { + j += 2; + }else { + int temp = A[j]; + A[j] = A[i]; + A[i] = temp; + i+=2; + j+=2; + } + + } + return A; + } + + +} diff --git a/Week_01/id_125/LeetCode_83_125.c b/Week_01/id_125/LeetCode_83_125.c new file mode 100644 index 00000000..9c76402f --- /dev/null +++ b/Week_01/id_125/LeetCode_83_125.c @@ -0,0 +1,20 @@ +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * struct ListNode *next; + * }; + */ +struct ListNode* deleteDuplicates(struct ListNode* head) { + struct ListNode *orig = head; + if (!head) + return head; + while(head && head->next) { + if(head->val == head->next->val) { + head->next = head->next->next; + } else { + head = head->next; + } + } + return orig; +} diff --git a/Week_01/id_125/LeetCode_905_125.c b/Week_01/id_125/LeetCode_905_125.c new file mode 100644 index 00000000..1a78df07 --- /dev/null +++ b/Week_01/id_125/LeetCode_905_125.c @@ -0,0 +1,33 @@ +/** + * Return an array of size *returnSize. + * Note: The returned array must be malloced, assume caller calls free(). + */ +int* sortArrayByParity(int* A, int ASize, int* returnSize) { + int *returnA = (int*)malloc(ASize*sizeof(int)); + int i, j, tmp; + for(i = 0, j = 0; i < ASize; i++) { + if(A[i]%2 == 0) { + returnA[j++] = A[i]; + } + } + for(i = 0; i= l2.Val{ +res = l2 +res.Next = mergeTwoLists(l1, l2.Next) +}else{ +res = l1 +res.Next = mergeTwoLists(l1.Next, l2) +} +return res +} diff --git a/Week_01/id_128/LeetCode_905_128.go b/Week_01/id_128/LeetCode_905_128.go new file mode 100644 index 00000000..df0e3cc0 --- /dev/null +++ b/Week_01/id_128/LeetCode_905_128.go @@ -0,0 +1,10 @@ +func sortArrayByParity(A []int) []int { + i := 0 + for j:=0;j map = new HashMap<>(); + int index = 0; + ListNode result = null; + while (head != null) { + Integer value = map.get(head); + if (value == null) { + map.put(head, index); + head = head.next; + } else { + result = head; + break; + } + } + return result; + } +} diff --git a/Week_01/id_129/LeetCode_153_129.java b/Week_01/id_129/LeetCode_153_129.java new file mode 100644 index 00000000..e14a8ff8 --- /dev/null +++ b/Week_01/id_129/LeetCode_153_129.java @@ -0,0 +1,19 @@ +public class LeetCode_153_129 { + public int findMin(int[] nums) { + int low = 0, mid; + int high = nums.length - 1; + if (high == 0) return nums[0]; + int min = nums[0]; + while (low <= high) { + mid = low + ((high - low) >> 1); + if (nums[low] <= nums[mid]) { + min = Math.min(nums[low], min); + low = mid + 1; + } else { + min = Math.min(nums[mid], min); + high = mid - 1; + } + } + return min; + } +} diff --git a/Week_01/id_129/LeetCode_20_129.java b/Week_01/id_129/LeetCode_20_129.java new file mode 100644 index 00000000..c1db9e12 --- /dev/null +++ b/Week_01/id_129/LeetCode_20_129.java @@ -0,0 +1,30 @@ +import java.util.Stack; + +public class LeetCode_20_129 { + public static boolean isValid(String s) { + char[] chars = s.toCharArray(); + Stack stack = new Stack<>(); + for (char c : chars) { + if ('(' == c || '[' == c || '{' == c) { + stack.push(c); + } else if (')' == c || ']' == c || '}' == c) { + if (stack.empty()) { + return false; + } + char e = stack.pop(); + if (!isSame(e, c)) { + return false; + } + } + } + if (stack.empty()) { + return true; + } else { + return false; + } + } + + private static boolean isSame(char c1, char c2) { + return (c1 == '(' && c2 == ')') || (c1 == '[' && c2 == ']') || (c1 == '{' && c2 == '}'); + } +} diff --git a/Week_01/id_129/LeetCode_21_129.java b/Week_01/id_129/LeetCode_21_129.java new file mode 100644 index 00000000..a9898080 --- /dev/null +++ b/Week_01/id_129/LeetCode_21_129.java @@ -0,0 +1,22 @@ +public class LeetCode_21_129 { + public static ListNode mergeTwoLists(ListNode l1, ListNode l2) { + ListNode dummyNode = new ListNode(0); + ListNode cur = dummyNode; + while (l1 != null && l2 != null) { + if (l1.val < l2.val) { + cur.next = l1; + l1 = l1.next; + } else { + cur.next = l2; + l2 = l2.next; + } + cur = cur.next; + } + if (l1 != null) { + cur.next = l1; + } else { + cur.next = l2; + } + return dummyNode.next; + } +} diff --git a/Week_01/id_129/LeetCode_24_129.java b/Week_01/id_129/LeetCode_24_129.java new file mode 100644 index 00000000..2d1ee11f --- /dev/null +++ b/Week_01/id_129/LeetCode_24_129.java @@ -0,0 +1,10 @@ +public class LeetCode_24_129 { + public static ListNode swapPairs(ListNode head) { + if (head == null || head.next == null) return head; + ListNode node = swapPairs(head.next.next); + ListNode cur = head.next; + head.next = node; + cur.next = head; + return cur; + } +} diff --git a/Week_01/id_129/LeetCode_2_129.java b/Week_01/id_129/LeetCode_2_129.java new file mode 100644 index 00000000..fe98e03a --- /dev/null +++ b/Week_01/id_129/LeetCode_2_129.java @@ -0,0 +1,14 @@ +public class LeetCode_2_129 { + public static ListNode deleteDuplicates(ListNode head) { + if (head == null) return head; + ListNode cursor = head; + while (cursor != null && cursor.next != null) { + if (cursor.val == cursor.next.val) { + cursor.next = cursor.next.next; + } else { + cursor = cursor.next; + } + } + return head; + } +} diff --git a/Week_01/id_129/LeetCode_503_129.java b/Week_01/id_129/LeetCode_503_129.java new file mode 100644 index 00000000..1796bd09 --- /dev/null +++ b/Week_01/id_129/LeetCode_503_129.java @@ -0,0 +1,21 @@ +import java.util.Arrays; +import java.util.Stack; + +public class LeetCode_503_129 { + public int[] nextGreaterElements(int[] nums) { + int length = nums.length; + Stack stack = new Stack<>(); + int[] result = new int[length]; + Arrays.fill(result, -1); + for (int i = 0; i < length * 2; i++) { + int cur = nums[i % length]; + while (!stack.empty() && nums[stack.peek()] < cur) { + result[stack.pop()] = cur; + } + if (i < length) { + stack.push(i); + } + } + return result; + } +} diff --git a/Week_01/id_129/LeetCode_687_129.java b/Week_01/id_129/LeetCode_687_129.java new file mode 100644 index 00000000..f60cd95f --- /dev/null +++ b/Week_01/id_129/LeetCode_687_129.java @@ -0,0 +1,27 @@ +public class LeetCode_687_129 { + int ans; + + public int longestUnivaluePath(TreeNode root) { + ans = 0; + arrowLength(root); + return ans; + } + + public int arrowLength(TreeNode root) { + if (root == null) return 0; + int arrowLeft = arrowLength(root.left); + int arrowRight = arrowLength(root.right); + if (root.left != null && root.right != null && root.left.val == root.right.val && root.left.val == root.val) { + ans = Math.max(ans, arrowLeft + arrowRight + 2); + } + int res = 0; + if (root.left != null && root.left.val == root.val) { + res = arrowLeft + 1; + } + if (root.right != null && root.right.val == root.val) { + res = Math.max(res, arrowRight + 1); + } + ans = Math.max(res, ans); + return res; + } +} diff --git a/Week_01/id_129/LeetCode_81_129.java b/Week_01/id_129/LeetCode_81_129.java new file mode 100644 index 00000000..22c74d6b --- /dev/null +++ b/Week_01/id_129/LeetCode_81_129.java @@ -0,0 +1,31 @@ +public class LeetCode_81_129 { + public boolean search(int[] nums, int target) { + if (nums == null || nums.length == 0) return false; + int low = 0, mid; + int high = nums.length - 1; + while (low <= high) { + if (nums[low] < nums[high] && (target < nums[low] || target > nums[high])) return false; + mid = low + ((high - low) >> 1); + if (nums[mid] == target) { + return true; + } + if (nums[low] == nums[mid] && nums[high] == nums[mid]) { + low++; + high--; + } else if (nums[low] <= nums[mid]) { + if (nums[low] <= target && target < nums[mid]) { + high = mid - 1; + } else { + low = mid + 1; + } + } else { + if (nums[mid] < target && target <= nums[high]) { + low = mid + 1; + } else { + high = mid - 1; + } + } + } + return false; + } +} diff --git a/Week_01/id_129/LeetCode_905_129.java b/Week_01/id_129/LeetCode_905_129.java new file mode 100644 index 00000000..3f9b5651 --- /dev/null +++ b/Week_01/id_129/LeetCode_905_129.java @@ -0,0 +1,24 @@ +public class LeetCode_905_129 { + public static int[] sortArrayByParity(int[] A) { + int start = 0; + int end = A.length - 1; + while (start != end) { + if (A[start] % 2 == 0) { + start++; + continue; + } + if (A[end] % 2 != 0) { + end--; + continue; + } + swap(A, start, end); + } + return A; + } + + public static void swap(int[] src, int a, int b) { + int temp = src[a]; + src[a] = src[b]; + src[b] = temp; + } +} diff --git a/Week_01/id_129/LeetCode_922_129.java b/Week_01/id_129/LeetCode_922_129.java new file mode 100644 index 00000000..b2871a0b --- /dev/null +++ b/Week_01/id_129/LeetCode_922_129.java @@ -0,0 +1,25 @@ +public class LeetCode_922_129 { + public int[] sortArrayByParityII(int[] A) { + int i = 0; + int j = 1; + int limit = A.length - 1; + while (i <= limit && j <= limit) { + if (A[i] % 2 == 0) { + i += 2; + continue; + } + if (A[j] % 2 != 0) { + j += 2; + continue; + } + swap(A, i, j); + } + return A; + } + + public void swap(int[] src, int a, int b) { + int temp = src[a]; + src[a] = src[b]; + src[b] = temp; + } +} diff --git a/Week_01/id_129/ListNode.java b/Week_01/id_129/ListNode.java new file mode 100644 index 00000000..daaefbe9 --- /dev/null +++ b/Week_01/id_129/ListNode.java @@ -0,0 +1,42 @@ +public class ListNode { + public int val; + public ListNode next; + + ListNode(int x) { + val = x; + } + + public static int[] stringToIntegerArray(String input) { + input = input.trim(); + input = input.substring(1, input.length() - 1); + if (input.length() == 0) { + return new int[0]; + } + + String[] parts = input.split(","); + int[] output = new int[parts.length]; + for (int index = 0; index < parts.length; index++) { + String part = parts[index].trim(); + output[index] = Integer.parseInt(part); + } + return output; + } + + public static ListNode stringToListNode(String input) { + // Generate array from the input + int[] nodeValues = stringToIntegerArray(input); + + // Now convert that list into linked list + ListNode dummyRoot = new ListNode(0); + ListNode ptr = dummyRoot; + for (int item : nodeValues) { + ptr.next = new ListNode(item); + ptr = ptr.next; + } + return dummyRoot.next; + } + + public static ListNode get1() { + return stringToListNode("[1,1,2]"); + } +} diff --git a/Week_01/id_129/TreeNode.java b/Week_01/id_129/TreeNode.java new file mode 100644 index 00000000..e08a2b87 --- /dev/null +++ b/Week_01/id_129/TreeNode.java @@ -0,0 +1,9 @@ +public class TreeNode { + int val; + TreeNode left; + TreeNode right; + + TreeNode(int x) { + val = x; + } +} \ No newline at end of file diff --git a/Week_01/id_13/LeetCode_20_13.java b/Week_01/id_13/LeetCode_20_13.java new file mode 100644 index 00000000..febd55e6 --- /dev/null +++ b/Week_01/id_13/LeetCode_20_13.java @@ -0,0 +1,27 @@ +package leetCode; + +import java.util.Stack; + +public class LeetCode_20_13 { + public boolean isValid(String s) { + Stack stack = new Stack<>(); + + for (char ch : s.toCharArray()) { + if (stack.empty()) { + stack.push(ch); + } else if (isMatch(stack.peek(), ch)) { + stack.pop(); + } else { + stack.push(ch); + } + } + + return stack.empty(); + } + + private boolean isMatch(char ch1, char ch2) { + return ((ch1 == '{' && ch2 == '}') + || ch1 == '[' && ch2 == ']' + || ch1 == '(' && ch2 == ')'); + } +} diff --git a/Week_01/id_13/LeetCode_21_13.java b/Week_01/id_13/LeetCode_21_13.java new file mode 100644 index 00000000..ea0dedbe --- /dev/null +++ b/Week_01/id_13/LeetCode_21_13.java @@ -0,0 +1,38 @@ +package leetCode; + +public class LeetCode_21_13 { + + public ListNode mergeTwoLists(ListNode l1, ListNode l2) { + ListNode dummy = new ListNode(0); + ListNode cur = dummy; + + while (l1 != null && l2 != null) { + 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 == null) { + cur.next = l2; + } else { + cur.next = l1; + } + + return dummy.next; + } + + public class ListNode { + int val; + ListNode next; + + ListNode(int x) { + val = x; + } + } +} diff --git a/Week_01/id_13/LeetCode_687_13.java b/Week_01/id_13/LeetCode_687_13.java new file mode 100644 index 00000000..d9c20601 --- /dev/null +++ b/Week_01/id_13/LeetCode_687_13.java @@ -0,0 +1,46 @@ +package leetCode; + +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ + +public class LeetCode_687_13 { + private int pathInt; + + public int longestUnivaluePath(TreeNode root) { + pathInt = 0; + _pathLength(root); + return pathInt; + } + + public int _pathLength(TreeNode node) { + if (node == null) return 0; + int left = _pathLength(node.left); + int right = _pathLength(node.right); + int pathLeft = 0, pathRight = 0; + if (node.left != null && node.left.val == node.val) { + pathLeft += left + 1; + } + if (node.right != null && node.right.val == node.val) { + pathRight += right + 1; + } + pathInt = Math.max(pathInt, pathLeft + pathRight); + return Math.max(pathLeft, pathRight); + } + + public class TreeNode { + int val; + TreeNode left; + TreeNode right; + + TreeNode(int x) { + val = x; + } + } +} diff --git a/Week_01/id_13/LeetCode_83_13.java b/Week_01/id_13/LeetCode_83_13.java new file mode 100644 index 00000000..84ad9cbe --- /dev/null +++ b/Week_01/id_13/LeetCode_83_13.java @@ -0,0 +1,38 @@ +package leetCode; + +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode(int x) { val = x; } + * } + */ + +public class LeetCode_83_13 { + + public ListNode deleteDuplicates(ListNode head) { + + ListNode cur = head; + + while (cur.next != null) { + if (cur.val == cur.next.val) { + cur.next = cur.next.next; + } else { + cur = cur.next; + } + } + + return head; + } + + public class ListNode { + int val; + ListNode next; + + ListNode(int x) { + val = x; + } + } + +} diff --git a/Week_01/id_13/LeetCode_905_13.java b/Week_01/id_13/LeetCode_905_13.java new file mode 100644 index 00000000..929662b9 --- /dev/null +++ b/Week_01/id_13/LeetCode_905_13.java @@ -0,0 +1,26 @@ +package leetCode; + +public class LeetCode_905_13 { + public int[] sortArrayByParity(int[] A) { + + int i = 0; + int j = A.length - 1; + + while (i < j) { + if (A[i] % 2 == 0) { + i++; + } else if (A[j] % 2 == 0) { + // swap(A[i],A[j]) + int temp = A[i]; + A[i] = A[j]; + A[j] = temp; + i++; + j--; + } else if (A[j] % 2 != 0) { + j--; + } + } + + return A; + } +} diff --git a/Week_01/id_13/LeetCode_922_13.java b/Week_01/id_13/LeetCode_922_13.java new file mode 100644 index 00000000..6c626fa8 --- /dev/null +++ b/Week_01/id_13/LeetCode_922_13.java @@ -0,0 +1,21 @@ +package leetCode; + +public class LeetCode_922_13 { + public int[] sortArrayByParityII(int[] A) { + int[] N = new int[A.length]; + int m = 0; + int k = 1; + + for (int a : A) { + if (a % 2 == 0) { + N[m] = a; + m += 2; + } else { + N[k] = a; + k += 2; + } + } + + return N; + } +} diff --git a/Week_01/id_130/LeetCode_83_130.js b/Week_01/id_130/LeetCode_83_130.js new file mode 100644 index 00000000..95cb79af --- /dev/null +++ b/Week_01/id_130/LeetCode_83_130.js @@ -0,0 +1,26 @@ +// https://leetcode.com/problems/remove-duplicates-from-sorted-list/ +/** + * Definition for singly-linked list. + * function ListNode(val) { + * this.val = val; + * this.next = null; + * } + */ +/** + * @param {ListNode} head + * @return {ListNode} + */ +var deleteDuplicates = function(head) { + if (!head) return head; + + let currentNode = head; + while (currentNode.next) { + if (currentNode.val === currentNode.next.val) { + currentNode.next = currentNode.next.next; + } else { + currentNode = currentNode.next; + } + } + + return head; +}; diff --git a/Week_01/id_130/LeetCode_905_130.js b/Week_01/id_130/LeetCode_905_130.js new file mode 100644 index 00000000..68fd0126 --- /dev/null +++ b/Week_01/id_130/LeetCode_905_130.js @@ -0,0 +1,17 @@ +// https://leetcode.com/problems/sort-array-by-parity/ +/** + * @param {number[]} A + * @return {number[]} + */ +var sortArrayByParity = function(A) { + const result = []; + for (let i = 0; i < A.length; i++) { + const currentVal = A[i]; + if (A[i] % 2 === 1) { + result.push(currentVal); + } else { + result.unshift(currentVal); + } + } + return result; +}; diff --git a/Week_01/id_130/NOTE.md b/Week_01/id_130/NOTE.md index c684e62f..37909ef2 100644 --- a/Week_01/id_130/NOTE.md +++ b/Week_01/id_130/NOTE.md @@ -1 +1,14 @@ -# 学习笔记 \ No newline at end of file +# 学习笔记 + +#### 关于专栏 + +- 还是要先过下专栏的知识点,熟悉数据结构后,才能选对数据结构 + +#### 关于算法题 + +- 一上来就想写出一个复杂度最低的代码有点天真 +- 不要一上来就开始写代码 + +#### 关于这次学习 + +- 坚持不掉队 diff --git a/Week_01/id_131/LeetCode_20_131.cpp b/Week_01/id_131/LeetCode_20_131.cpp new file mode 100644 index 00000000..720aff01 --- /dev/null +++ b/Week_01/id_131/LeetCode_20_131.cpp @@ -0,0 +1,65 @@ +class Solution { +public: + bool isMatchStack(stack &strStack, char c) + { + if(strStack.empty()) return false; + + switch(c) + { + case ')': + { + if('(' == strStack.top()) + { + strStack.pop(); + return true; + } + break; + } + case '}': + { + if('{' == strStack.top()) + { + strStack.pop(); + return true; + } + break; + } + case ']': + { + if('[' == strStack.top()) + { + strStack.pop(); + return true; + } + break; + } + } + return false; + } + + bool isValid(string s) + { + if(s.empty()) return true; + + stack strStack; + for(int i = 0; i < s.size(); ++i) + { + if( (s[i] == '(') || (s[i] == '[') || (s[i] == '{') ) + { + strStack.push(s[i]); + } + else if( !isMatchStack(strStack,s[i]) ) + { + return false; + } + } + if(strStack.empty()) + { + return true; + } + else + { + return false; + } + } +}; \ No newline at end of file diff --git a/Week_01/id_131/LeetCode_21_131.cpp b/Week_01/id_131/LeetCode_21_131.cpp new file mode 100644 index 00000000..b16201bc --- /dev/null +++ b/Week_01/id_131/LeetCode_21_131.cpp @@ -0,0 +1,43 @@ +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode(int x) : val(x), next(NULL) {} + * }; + */ +class Solution { +public: + ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { + ListNode* mergeNode = new ListNode(0); + ListNode* newNode = mergeNode; + while ( l1 !=NULL && l2 != NULL) + { + if(l1->val < l2->val) + { + newNode->next = l1; + newNode = newNode->next; + l1 = l1->next; + } + else + { + newNode->next = l2; + newNode = newNode->next; + l2 = l2->next; + } + } + while(l1 != NULL) + { + newNode->next = l1; + newNode = newNode->next; + l1 = l1->next; + } + while(l2 != NULL) + { + newNode->next = l2; + newNode = newNode->next; + l2 = l2->next; + } + return mergeNode->next; + } +}; \ No newline at end of file diff --git a/Week_01/id_131/LeetCode_242_131.cpp b/Week_01/id_131/LeetCode_242_131.cpp new file mode 100644 index 00000000..2af94a3e --- /dev/null +++ b/Week_01/id_131/LeetCode_242_131.cpp @@ -0,0 +1,17 @@ +class Solution { +public: + bool isAnagram(string s, string t) { + if(s.size() != t.size()) return false; + int strCount[26] = {0}; + for(int indexStr = 0; indexStr < s.size(); ++indexStr) + { + strCount[s[indexStr]-'a'] += 1; + strCount[t[indexStr]-'a'] -= 1; + } + for(int indexC = 0; indexC < 26; ++indexC) + { + if(strCount[indexC] != 0) return false; + } + return true; + } +}; \ No newline at end of file diff --git a/Week_01/id_131/LeetCode_441_131.cpp b/Week_01/id_131/LeetCode_441_131.cpp new file mode 100644 index 00000000..91f27aa7 --- /dev/null +++ b/Week_01/id_131/LeetCode_441_131.cpp @@ -0,0 +1,41 @@ +class Solution { +public: + int findSuitData(vector& unorderV, int index) + { + if (unorderV.empty()) + { + unorderV.push_back(index); + return -1; + } + int lastIndex = unorderV[unorderV.size() - 1]; + if (index % 2 != lastIndex % 2) + { + unorderV.pop_back(); + return lastIndex; + } + else + { + unorderV.push_back(index); + } + return -1; + } + + vector sortArrayByParityII(vector& A) { + vector unorderV; + for (int begin = 0; begin < A.size(); ++begin) + { + if (begin % 2 != A[begin] % 2) + { + int i = findSuitData(unorderV, begin); + if (i >= 0) + { + int tmpData = A[begin]; + A[begin] = A[i]; + A[i] = tmpData; + } + } + } + return A; + } + +}; \ No newline at end of file diff --git a/Week_01/id_131/LeetCode_687_131.cpp b/Week_01/id_131/LeetCode_687_131.cpp new file mode 100644 index 00000000..8c929135 --- /dev/null +++ b/Week_01/id_131/LeetCode_687_131.cpp @@ -0,0 +1,40 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} + * }; + 㷨 + + getMaxLen Ϊӽڵ node ͷijȡ node.Left ڵ node ֵͬ +ֵͻ 1 + getMaxLen node.right ڵҲһ + +Ǽ󳤶ʱѡ𰸽Ǹýڵϵļͷ֮͡ǽЩѡ𰸼¼Ѵ𰸡 + */ +class Solution { + +private: + int maxLen = 0; + +public: + int longestUnivaluePath(TreeNode* root) + { + if(NULL == root) return 0; + getMaxLen(root, root->val); + return maxLen; + } + int getMaxLen(TreeNode* root, int val) + { + if(NULL == root) return 0; + int leftLen = getMaxLen(root->left, root->val); + int rightLen = getMaxLen(root->right, root->val); + maxLen = std::max(maxLen, leftLen+rightLen); + if(root->val == val) + { + return std::max(leftLen, rightLen) + 1; + } + return 0; + } +}; \ No newline at end of file diff --git a/Week_01/id_131/LeetCode_83_131.cpp b/Week_01/id_131/LeetCode_83_131.cpp new file mode 100644 index 00000000..e56bb601 --- /dev/null +++ b/Week_01/id_131/LeetCode_83_131.cpp @@ -0,0 +1,26 @@ +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode(int x) : val(x), next(NULL) {} + * }; + */ +class Solution { +public: + ListNode* deleteDuplicates(ListNode* head) { + ListNode* data = head; + while(data != NULL && data->next != NULL) + { + if(data->val == data->next->val) + { + data->next = data->next->next; + } + else + { + data = data->next; + } + } + return head; + } +}; \ No newline at end of file diff --git a/Week_01/id_131/LeetCode_905_131.cpp b/Week_01/id_131/LeetCode_905_131.cpp new file mode 100644 index 00000000..c7f89654 --- /dev/null +++ b/Week_01/id_131/LeetCode_905_131.cpp @@ -0,0 +1,21 @@ +class Solution { +public: + vector sortArrayByParity(vector& A) { + int begin = 0, end = A.size()-1; + while(begin < end) + { + if(A[begin]%2 == 0) ++begin; + if(A[end]%2 == 1) --end; + if(begin >= end) break; + if((A[begin]%2 == 1) && (A[end]%2 == 0)) + { + A[begin] ^= A[end]; + A[end] ^= A[begin]; + A[begin] ^= A[end]; + ++begin; + --end; + } + } + return A; + } +}; \ No newline at end of file diff --git a/Week_01/id_131/LeetCode_922_131.cpp b/Week_01/id_131/LeetCode_922_131.cpp new file mode 100644 index 00000000..91f27aa7 --- /dev/null +++ b/Week_01/id_131/LeetCode_922_131.cpp @@ -0,0 +1,41 @@ +class Solution { +public: + int findSuitData(vector& unorderV, int index) + { + if (unorderV.empty()) + { + unorderV.push_back(index); + return -1; + } + int lastIndex = unorderV[unorderV.size() - 1]; + if (index % 2 != lastIndex % 2) + { + unorderV.pop_back(); + return lastIndex; + } + else + { + unorderV.push_back(index); + } + return -1; + } + + vector sortArrayByParityII(vector& A) { + vector unorderV; + for (int begin = 0; begin < A.size(); ++begin) + { + if (begin % 2 != A[begin] % 2) + { + int i = findSuitData(unorderV, begin); + if (i >= 0) + { + int tmpData = A[begin]; + A[begin] = A[i]; + A[i] = tmpData; + } + } + } + return A; + } + +}; \ No newline at end of file diff --git a/Week_01/id_134/LeetCode_142_134.java b/Week_01/id_134/LeetCode_142_134.java new file mode 100644 index 00000000..7e11a176 --- /dev/null +++ b/Week_01/id_134/LeetCode_142_134.java @@ -0,0 +1,35 @@ +//https://leetcode.com/problems/linked-list-cycle-ii/ +/** + * Definition for singly-linked list. + * class ListNode { + * int val; + * ListNode next; + * ListNode(int x) { + * val = x; + * next = null; + * } + * } + */ +public class Solution { + public ListNode detectCycle(ListNode head) { + if (head == null) + return null; + ListNode fast = head, slow = head; + boolean flag = true; + while (true) { + if (fast == null || fast.next == null) + return null; + if (!flag && fast == slow) + break; + fast = fast.next.next; + slow = slow.next; + flag = false; + } + fast = head; + while (fast != slow) { + fast = fast.next; + slow = slow.next; + } + return fast; + } +} \ No newline at end of file diff --git a/Week_01/id_134/LeetCode_20_134.java b/Week_01/id_134/LeetCode_20_134.java new file mode 100644 index 00000000..9a8deb00 --- /dev/null +++ b/Week_01/id_134/LeetCode_20_134.java @@ -0,0 +1,31 @@ +//https://leetcode.com/problems/valid-parentheses/ +public class Solution { + public boolean isValid(String s) { + Stack stack = new Stack<>(); + + for(int i=0; i nums[i]) { + ret[i] = nums[j]; + flag = 1; + break; + } + } + if (flag == 0) { + for (int k=0; k nums[i]) { + ret[i] = nums[k]; + break; + } + } + } + } + return ret; + } +} \ No newline at end of file diff --git a/Week_01/id_134/LeetCode_83_134.java b/Week_01/id_134/LeetCode_83_134.java new file mode 100644 index 00000000..fbf7bdfd --- /dev/null +++ b/Week_01/id_134/LeetCode_83_134.java @@ -0,0 +1,28 @@ +//https://leetcode.com/problems/remove-duplicates-from-sorted-list/ + +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode(int x) { val = x; } + * } + */ +class Solution { + public ListNode deleteDuplicates(ListNode head) { + if (head == null) + return null; + ListNode prev = head, cur = head.next; + while (cur != null) { + if (cur.val == prev.val) { + prev.next = cur.next; + cur.next = null; + cur = prev.next; + } else { + prev = prev.next; + cur = cur.next; + } + } + return head; + } +} \ No newline at end of file diff --git a/Week_01/id_134/LeetCode_905_134.java b/Week_01/id_134/LeetCode_905_134.java new file mode 100644 index 00000000..8c59406c --- /dev/null +++ b/Week_01/id_134/LeetCode_905_134.java @@ -0,0 +1,24 @@ +//https://leetcode.com/problems/sort-array-by-parity/ +class Solution { + public int[] sortArrayByParity(int[] A) { + if (A == null) + return null; + int left = 0, right = A.length-1; + while (left < right) { + if ((A[left] & 1) == 0) { + left ++; + continue; + } + if ((A[right] & 1) == 1) { + right --; + continue; + } + int tmp = A[left]; + A[left] = A[right]; + A[right] = tmp; + left ++; + right --; + } + return A; + } +} \ No newline at end of file diff --git a/Week_01/id_134/LeetCode_922_134.java b/Week_01/id_134/LeetCode_922_134.java new file mode 100644 index 00000000..ecf033f0 --- /dev/null +++ b/Week_01/id_134/LeetCode_922_134.java @@ -0,0 +1,24 @@ +//https://leetcode.com/problems/sort-array-by-parity-ii/ +class Solution { + public int[] sortArrayByParityII(int[] A) { + if (A == null || A.length <= 1) + return A; + int even = 0, odd = 1; + while (even < A.length && odd < A.length) { + if ((A[even] & 1) == 0) { + even += 2; + continue; + } + if ((A[odd] & 1) == 1) { + odd += 2; + continue; + } + int tmp = A[even]; + A[even] = A[odd]; + A[odd] = tmp; + even += 2; + odd += 2; + } + return A; + } +} \ No newline at end of file diff --git a/Week_01/id_135/LeetCode_81_135.java b/Week_01/id_135/LeetCode_81_135.java new file mode 100644 index 00000000..61ac5c01 --- /dev/null +++ b/Week_01/id_135/LeetCode_81_135.java @@ -0,0 +1,9 @@ +class Solution { + public boolean search(int[] nums, int target) { + for(int i = 0; i < nums.length; i++){ + if(nums[i] == target) + return true; + } + return false; + } +} \ No newline at end of file diff --git a/Week_01/id_135/LeetCode_905_135.java b/Week_01/id_135/LeetCode_905_135.java new file mode 100644 index 00000000..f9eff27e --- /dev/null +++ b/Week_01/id_135/LeetCode_905_135.java @@ -0,0 +1,17 @@ +class Solution { + public int[] sortArrayByParity(int[] A) { + if(A == null || A.length == 1) + return A; + int x = 0; + int y = A.length - 1; + int[] res = new int[A.length]; + for(int i = 0; i < A.length; i++){ + if(A[i] % 2 == 0){ + res[x++] = A[i]; + }else{ + res[y--] = A[i]; + } + } + return res; + } +} \ No newline at end of file diff --git a/Week_01/id_136/LeetCode_21_136.js b/Week_01/id_136/LeetCode_21_136.js new file mode 100644 index 00000000..3feb316c --- /dev/null +++ b/Week_01/id_136/LeetCode_21_136.js @@ -0,0 +1,36 @@ +/** + * Definition for singly-linked list. + * function ListNode(val) { + * this.val = val; + * this.next = null; + * } + */ +/** + * @param {ListNode} l1 + * @param {ListNode} l2 + * @return {ListNode} + */ +var mergeTwoLists = function(l1, l2) { + let p1 =l1; + let p2 =l2; + let dummy = new ListNode(null); + dummy.next = p1; + let prev = dummy; + while(p1 && p2){ + if(p1.val < p2.val){ + prev = p1; + p1 = p1.next; + }else{ + prev.next = p2; + p2 = p2.next; + prev = prev.next; + prev.next = p1; + } + } + if(p2){ + prev.next = p2; + } + + return dummy.next; + +}; \ No newline at end of file diff --git a/Week_01/id_136/LeetCode_83_136.js b/Week_01/id_136/LeetCode_83_136.js new file mode 100644 index 00000000..6a5b5e27 --- /dev/null +++ b/Week_01/id_136/LeetCode_83_136.js @@ -0,0 +1,22 @@ +/** + * Definition for singly-linked list. + * function ListNode(val) { + * this.val = val; + * this.next = null; + * } + */ +/** + * @param {ListNode} head + * @return {ListNode} + */ +var deleteDuplicates = function(head) { + let current = head; + while (current != null && current.next != null) { + if (current.next.val == current.val) { + current.next = current.next.next; + } else { + current = current.next; + } + } + return head; +}; \ No newline at end of file diff --git a/Week_01/id_137/LeetCode_441_137.py b/Week_01/id_137/LeetCode_441_137.py new file mode 100644 index 00000000..95d612ee --- /dev/null +++ b/Week_01/id_137/LeetCode_441_137.py @@ -0,0 +1,94 @@ +"https://leetcode-cn.com/problems/arranging-coins/" +"Author : Shaodong Song" +"Date : 2019-04-20" + +""" +You have a total of n coins that you want to form in a staircase shape, where every k-th row must have exactly k coins. + +Given n, find the total number of full staircase rows that can be formed. + +n is a non-negative integer and fits within the range of a 32-bit signed integer. + +Example 1: + +n = 5 + +The coins can form the following rows: +* +* * +* * + +Because the 3rd row is incomplete, we return 2. +""" + +class Solution(object): + def arrangeCoins(self, n): + """ + :type n: int + :rtype: int + """ + + if n == 0: + return 0 + + if n == 1: + return 1 + + lo = 0 + mid = 0 + hi = n + + while hi - lo > 1: + mid = (lo + hi) >> 1 + sum_num = mid * (mid + 1) >> 1 + + if sum_num == n: + return mid + elif sum_num > n: + hi = mid + else: + lo = mid + + return lo + + +class Solution1(object): + def arrangeCoins(self, n): + """ + :type n: int + :rtype: int + """ + + i = 1 + num = n + while num >= i: + num -= i + i += 1 + + return i - 1 + + +class Solution2(object): + def arrangeCoins(self, n): + """ + :type n: int + :rtype: int + """ + + num = int((2 * n) ** 0.5) + if n < 2 or (1 + num) * num / 2 <= n: + return num + else: + return num - 1 + + +so = Solution() +so1 = Solution() +so2 = Solution() + +print "arrangeCoins 10 = %d line" % so.arrangeCoins(10) +print "arrangeCoins 9 = %d line" % so1.arrangeCoins(9) +print "arrangeCoins 8 = %d line" % so2.arrangeCoins(8) + + + diff --git a/Week_01/id_137/LeetCode_687_137.py b/Week_01/id_137/LeetCode_687_137.py new file mode 100644 index 00000000..5c293b20 --- /dev/null +++ b/Week_01/id_137/LeetCode_687_137.py @@ -0,0 +1,91 @@ +"https://leetcode-cn.com/problems/longest-univalue-path/" +"Author : Shaodong Song" +"Date : 2019-04-20" + +""" +Given a binary tree, find the length of the longest path where each node in the path has the same value. This path may or may not pass through the root. + +Note: The length of path between two nodes is represented by the number of edges between them. + +--> Example 1: + +Input: + + 1 + / \ + 2 1 + +Output: 1 + +--> Example 2: + +Input: + + 1 + / \ + 1 1 + +Output: 2 +""" + +"Definition for a binary tree node." +class TreeNode(object): + def __init__(self, x): + self.val = x + self.left = None + self.right = None + +class Solution(object): + + max_path = 0; + + def findUnivaluePathCore(self, root, val): + if root == None: + return 0 + + left = self.findUnivaluePathCore(root.left, root.val) + right = self.findUnivaluePathCore(root.right, root.val) + + self.max_path = max(self.max_path, left + right) + + " when the current node and the parent node are the same," + " return longest univalue path length that can be formed by the current node." + " otherwise return 0." + + if root.val == val: + return max(left, right) + 1 + + return 0 + + def longestUnivaluePath(self, root): + """ + :type root: TreeNode + :rtype: int + """ + if root == None: + return 0 + + self.findUnivaluePathCore(root, root.val) + + return self.max_path + + +root = TreeNode(1) + +"case 1" +""" +root.left = TreeNode(2) +root.right = TreeNode(1) +""" + +"case 2" +root.left = TreeNode(1) +root.right = TreeNode(1) + +"case n" +"..." + +so = Solution() + +print "longestUnivaluePath = %d" % so.longestUnivaluePath(root) + diff --git a/Week_01/id_139/LeetCode_142_139.java b/Week_01/id_139/LeetCode_142_139.java new file mode 100644 index 00000000..64712bb0 --- /dev/null +++ b/Week_01/id_139/LeetCode_142_139.java @@ -0,0 +1,54 @@ +1. set +//执行用时 : 17 ms, 在Linked List Cycle II的Java提交中击败了18.90% 的用户 +//内存消耗 : 35.9 MB, 在Linked List Cycle II的Java提交中击败了6.94% 的用户 + +public class Solution { + public ListNode detectCycle(ListNode head) { + Set set = new HashSet(); + while(head != null){ + if (set.contains(head)) return head; + else{ + set.add(head); + head = head.next; + } + } + return null; + } +} + + + + +2,快慢指针 +解题思路:分两个步骤,首先通过快慢指针的方法判断链表是否有环;接下来如果有环, +则寻找入环的第一个节点。具体的方法为,首先假定链表起点到入环的第一个节点A的长度为a【未知】, +到快慢指针相遇的节点B的长度为(a + b)【这个长度是已知的】。现在我们想知道a的值, +注意到快指针p2始终是慢指针p走过长度的2倍,所以慢指针p从B继续走(a + b)又能回到B点, +如果只走a个长度就能回到节点A。但是a的值是不知道的,解决思路是曲线救国,注意到起点到A的长度是a, +那么可以用一个从起点开始的新指针q和从节点B开始的慢指针p同步走,相遇的地方必然是入环的第一个节点A。 +文字有点绕,画个图就一目了然了~~· + +public class Solution { public ListNode detectCycle(ListNode head) { if (head == null) return null; + ListNode p = head, p2 = head; + boolean hasCycle = false; + while (p2.next != null && p2.next.next != null) { + p = p.next; + p2 = p2.next.next; + if (p == p2) { + hasCycle = true; + break; + } + } + + // 步骤二:若有环,找到入环开始的节点 + if (hasCycle) { + ListNode q = head; + while (p != q) { + p = p.next; + q = q.next; + } + return q; + } else + return null; +} + diff --git a/Week_01/id_139/LeetCode_153_139.java b/Week_01/id_139/LeetCode_153_139.java new file mode 100644 index 00000000..38a78964 --- /dev/null +++ b/Week_01/id_139/LeetCode_153_139.java @@ -0,0 +1,13 @@ +//执行用时 : 1 ms, 在Find Minimum in Rotated Sorted Array的Java提交中击败了92.41% 的用户 +//内存消耗 : 37.5 MB, 在Find Minimum in Rotated Sorted Array的Java提交中击败了7.22%的用户 + +class Solution { + public int findMin(int[] nums) { + int i = 1; + int min = nums[0]; + for(;inums[i]) min=nums[i]; + } + return min; + } +} diff --git a/Week_01/id_139/LeetCode_21_139.java b/Week_01/id_139/LeetCode_21_139.java new file mode 100644 index 00000000..96b6cb09 --- /dev/null +++ b/Week_01/id_139/LeetCode_21_139.java @@ -0,0 +1,57 @@ +1,申请额外空间 + + +//执行用时 : 3 ms, 在Sort Array By Parity的Java提交中击败了99.59% 的用户 +//内存消耗 : 46.5 MB, 在Sort Array By Parity的Java提交中击败了68.41% 的用户 + +class Solution { + public int[] sortArrayByParity(int[] A) { + + int j = A.length; + if (j<=1) return A; + int[] B = new int[j]; + + int x=0; + int y=j-1; + + for(int i=0; i40m + while(x <= n){ + j = 0; + + //拿到k个节点 + for (;j set = new HashSet<>(); + ListNode pre = new ListNode(-1); + pre.next = head; + ListNode p = head; + + while( p != null ){ + if (set.contains(p.val)){ + pre.next = p.next; + p = p.next; + } + else{ + set.add(p.val); + pre = p; + p = p.next; + } + } + return head; + } +} + + +//3,递归(时间效率很差) +//执行用时 : 3 ms, 在Remove Duplicates from Sorted List的Java提交中击败了6.53% 的用户 +//内存消耗 : 36.3 MB, 在Remove Duplicates from Sorted List的Java提交中击败了74.62% 的用户 +class Solution { + public ListNode deleteDuplicates(ListNode head) { + if (head == null || head.next == null) return head; + ListNode p = deleteDuplicates(head.next); + if (head.val == p.val) head.next = p.next; + return head; + } +} + +//1,找终止条件:当head指向链表只剩一个元素的时候,自然是不可能重复的,因此return +//2,想想应该返回什么值:应该返回的自然是已经去重的链表的头节点 +//3,每一步要做什么:宏观上考虑,此时head.next已经指向一个去重的链表了,而根据第二步,我应该返回一个去重的链表的头节点。 +//因此这一步应该做的是判断当前的head和head.next是否相等,如果相等则说明重了,返回head.next,否则返回head \ No newline at end of file diff --git a/Week_01/id_139/LeetCode_922_139.java b/Week_01/id_139/LeetCode_922_139.java new file mode 100644 index 00000000..9128ce03 --- /dev/null +++ b/Week_01/id_139/LeetCode_922_139.java @@ -0,0 +1,64 @@ +1,建立新数组 + +//执行用时 : 6 ms, 在Sort Array By Parity II的Java提交中击败了83.69% 的用户 +//内存消耗 : 48.9 MB, 在Sort Array By Parity II的Java提交中击败了67.91% 的用户 + +class Solution { + public int[] sortArrayByParityII(int[] A) { + if(A == null || A.length == 1) return A; + int k = A.length-1; + int[] B = new int[A.length]; + + int i = 0; + int j = 0; + int x = 1; + while(i<=k){ + if(A[i]%2 == 0){ + B[j] = A[i]; + j=j+2; + } + else{ + B[x] = A[i]; + x = x+2; + } + i++; + } + return B; + } +} + + + +2, +//执行用时 : 7 ms, 在Sort Array By Parity II的Java提交中击败了77.23% 的用户 +//内存消耗 : 49.7 MB, 在Sort Array By Parity II的Java提交中击败了51.80% 的用户 + +//执行用时 : 5 ms, 在Sort Array By Parity II的Java提交中击败了93.39% 的用户 +//内存消耗 : 41.5 MB, 在Sort Array By Parity II的Java提交中击败了92.67% 的用户 + +//执行用时 : 7 ms, 在Sort Array By Parity II的Java提交中击败了77.23% 的用户 +//内存消耗 : 52.3 MB, 在Sort Array By Parity II的Java提交中击败了9.49% 的用户 +class Solution { + public int[] sortArrayByParityII(int[] A) { + if(A == null || A.length == 1) return A; + int k = A.length-1; + + int i = 0; + int j = 1; + + while(i<=k && j<=k){ + if(A[i]%2 != 0 && A[j]%2 == 0 ){ + int temp = A[i]; + A[i] = A[j]; + A[j]=temp; + i = i+2; + j = j+2; + } + else{ + if(A[i]%2==0) i = i+2; + if(A[j]%2!=0) j = j+2; + } + } + return A; + } +} \ No newline at end of file diff --git a/Week_01/id_139/NOTE.md b/Week_01/id_139/NOTE.md index c684e62f..28903b7c 100644 --- a/Week_01/id_139/NOTE.md +++ b/Week_01/id_139/NOTE.md @@ -1 +1,2 @@ -# 学习笔记 \ No newline at end of file +# 学习笔记 +已在各.java文件中 diff --git a/Week_01/id_140/Leetcode_687_140.java b/Week_01/id_140/Leetcode_687_140.java new file mode 100644 index 00000000..d31c62d0 --- /dev/null +++ b/Week_01/id_140/Leetcode_687_140.java @@ -0,0 +1,90 @@ +/** + * 给定一个二叉树,找到最长的路径,这个路径中的每个节点具有相同值。 这条路径可以经过也可以不经过根节点。 + *

+ * 注意:两个节点之间的路径长度由它们之间的边数表示。 + *

+ * 示例 1: + *

+ * 输入: + *

+ * 5 + * / \ + * 4 5 + * / \ \ + * 1 1 5 + * 输出: + *

+ * 2 + * 示例 2: + *

+ * 输入: + *

+ * 1 + * / \ + * 4 5 + * / \ \ + * 4 4 5 + * 输出: + *

+ * 2 + * 注意: 给定的二叉树不超过10000个结点。 树的高度不超过1000。 + */ +public class Leetcode_687_140 { + /** + * 调用入口 + * @param root + * @return + */ + public int longestUnivaluePath(TreeNode root) { + int[] answer = new int[1]; + dfs(root, answer); + return answer[0]; + } + + /** + * 返回数值一样最长的那个节点的值 + * @param root + * @param answer + * @return + */ + private int dfs(TreeNode root, int[] answer) { + if (root == null) { + return 0; + } + + int leftLength = dfs(root.left, answer); + int rightLength = dfs(root.right, answer); + + + int maxUnival = 0; + if (root.left != null && root.val == root.left.val) { + maxUnival += leftLength + 1; + } + if (root.right != null && root.val == root.right.val) { + maxUnival += rightLength + 1; + } + answer[0] = Math.max(answer[0], maxUnival); + + + int returnVal = 0; + if (root.left != null && root.left.val == root.val) { + returnVal = leftLength + 1; + } + + if (root.right != null && root.right.val == root.val) { + returnVal = Math.max(returnVal, rightLength + 1); + } + + return returnVal; + } + + public class TreeNode { + int val; + TreeNode left; + TreeNode right; + + TreeNode(int x) { + val = x; + } + } +} diff --git a/Week_01/id_140/Leetcode_905_140.java b/Week_01/id_140/Leetcode_905_140.java new file mode 100644 index 00000000..50afd645 --- /dev/null +++ b/Week_01/id_140/Leetcode_905_140.java @@ -0,0 +1,47 @@ +/** + * 给定一个非负整数数组 A,返回一个由 A 的所有偶数元素组成的数组,后面跟 A 的所有奇数元素。 + * + * 你可以返回满足此条件的任何数组作为答案。 + * + * + * + * 示例: + * + * 输入:[3,1,2,4] + * 输出:[2,4,3,1] + * 输出 [4,2,3,1],[2,4,1,3] 和 [4,2,1,3] 也会被接受。 + * + * + * 提示: + * + * 1 <= A.length <= 5000 + * 0 <= A[i] <= 5000 + */ +public class Leetcode_905_140 { + + /** + * 程序入口 + * @param A + * @return + */ + public int[] sortArrayByParity(int[] A) { + if (A == null || A.length == 0) { + return new int[0]; + } + + int even = 0; + int odd = A.length - 1; + int[] ret = new int[A.length]; + int i = 0; + while (even <= odd) { + if (A[i] % 2 == 1) { + ret[odd--] = A[i]; + } else { + ret[even++] = A[i]; + } + i++; + } + return ret; + } + +} diff --git a/Week_01/id_142/LeetCode_20_142.java b/Week_01/id_142/LeetCode_20_142.java new file mode 100644 index 00000000..574fd66c --- /dev/null +++ b/Week_01/id_142/LeetCode_20_142.java @@ -0,0 +1,34 @@ +import java.util.Deque; +import java.util.ArrayDeque; + +class Solution { + + public boolean isValid(String s) { + if (s.length() == 0) { + return true; + } + boolean ret = false; + Deque stack = new ArrayDeque(); + for (int i = 0; i < s.length(); i++) { + char c = s.charAt(i); + if (c == '(' || c == '{' || c == '[') { + stack.addFirst(c); + } else { + if (stack.isEmpty()) { + break; + } + char p = stack.removeFirst(); + if (!(c == ')' && p == '(') + && !(c == ']' && p == '[') + && !(c == '}' && p == '{')) { + break; + } + if (i == s.length() - 1 && stack.isEmpty()) { + ret = true; + } + } + + } + return ret; + } +} \ No newline at end of file diff --git a/Week_01/id_142/LeetCode_21_142.java b/Week_01/id_142/LeetCode_21_142.java new file mode 100644 index 00000000..f4f38daf --- /dev/null +++ b/Week_01/id_142/LeetCode_21_142.java @@ -0,0 +1,39 @@ +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode(int x) { val = x; } + * } + */ +class Solution { + + public ListNode mergeTwoLists(ListNode l1, ListNode l2) { + ListNode ret = null; + ListNode l = null; + while (l1 != null || l2 != null) { + ListNode curr; + if (l1 == null) { + curr = l2; + l2 = l2.next; + } else if (l2 == null) { + curr = l1; + l1 = l1.next; + } else if (l1.val <= l2.val) { + curr = l1; + l1 = l1.next; + } else { + curr = l2; + l2 = l2.next; + } + if (ret == null) { + ret = new ListNode(curr.val); + l = ret; + } else { + l.next = new ListNode(curr.val); + l = l.next; + } + } + return ret; + } +} diff --git a/Week_01/id_142/LeetCode_83_142.java b/Week_01/id_142/LeetCode_83_142.java new file mode 100644 index 00000000..c797311f --- /dev/null +++ b/Week_01/id_142/LeetCode_83_142.java @@ -0,0 +1,25 @@ +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode(int x) { val = x; } + * } + */ +class Solution { + + public ListNode deleteDuplicates(ListNode head) { + if (head == null) { + return null; + } + ListNode ret = head; + while (head.next != null) { + if (head.val == head.next.val) { + head.next = head.next.next; + } else { + head = head.next; + } + } + return ret; + } +} diff --git a/Week_01/id_142/LeetCode_905_142.java b/Week_01/id_142/LeetCode_905_142.java new file mode 100644 index 00000000..efb4d1dc --- /dev/null +++ b/Week_01/id_142/LeetCode_905_142.java @@ -0,0 +1,21 @@ +class Solution { + + public int[] sortArrayByParity(int[] A) { + int p = 0; + int q = A.length - 1; + while (p < q) { + if (A[p] % 2 == 0) { + p++; + } else if (A[q] % 2 == 0) { + int temp = A[q]; + A[q] = A[p]; + A[p] = temp; + p++; + q--; + } else { + q--; + } + } + return A; + } +} diff --git a/Week_01/id_144/NOTE.md b/Week_01/id_144/NOTE.md index c684e62f..822465bc 100644 --- a/Week_01/id_144/NOTE.md +++ b/Week_01/id_144/NOTE.md @@ -1 +1,4 @@ -# 学习笔记 \ No newline at end of file +# 学习笔记 +这周比较忙,草草的完成了两道简单题,也是第一次在leetcode上刷题,以后会养成习惯。 +周末会把视频课补上,再在leetcode上刷几道题吧。 +两道题都是整数与字符串的转换处理,没什么难度。 diff --git a/Week_01/id_144/leetcode_83_144.py b/Week_01/id_144/leetcode_83_144.py new file mode 100644 index 00000000..a1bd5235 --- /dev/null +++ b/Week_01/id_144/leetcode_83_144.py @@ -0,0 +1,20 @@ +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, x): +# self.val = x +# self.next = None + +class Solution: + def deleteDuplicates(self, head: ListNode) -> ListNode: + if not head: + return head + p = head + q = head.next + while q: + if q.val != p.val: + p.next = q + p = p.next + q = q.next + if p!= q: + p.next = None + return head \ No newline at end of file diff --git a/Week_01/id_144/leetcode_905_144.py b/Week_01/id_144/leetcode_905_144.py new file mode 100644 index 00000000..13d185f9 --- /dev/null +++ b/Week_01/id_144/leetcode_905_144.py @@ -0,0 +1,11 @@ +class Solution: + def sortArrayByParity(self, A: List[int]) -> List[int]: + s1 = [] + s2 = [] + for a in A: + if a %2 == 0: + s1.append(a) + else: + s2.append(a) + return s1 + s2 + \ No newline at end of file diff --git a/Week_01/id_145/LeetCode_20_145.cpp b/Week_01/id_145/LeetCode_20_145.cpp new file mode 100644 index 00000000..a2aeed67 --- /dev/null +++ b/Week_01/id_145/LeetCode_20_145.cpp @@ -0,0 +1,18 @@ +class Solution { +public: + bool isValid(string s) { + map m; + m[')'] = '('; + m[']'] = '['; + m['}'] = '{'; + stack my_stack; + for(int i; i < s.size(); ++i) { + if(!m.count(s[i])) my_stack.push(s[i]); + if(m.count(s[i]) && my_stack.empty()) return false; + if(m.count(s[i]) && my_stack.top() != m[s[i]]) return false; + if(m.count(s[i]) && my_stack.top() == m[s[i]]) my_stack.pop(); + } + return my_stack.empty(); + + } +}; \ No newline at end of file diff --git a/Week_01/id_145/LeetCode_24_145.cpp b/Week_01/id_145/LeetCode_24_145.cpp new file mode 100644 index 00000000..12abf3ef --- /dev/null +++ b/Week_01/id_145/LeetCode_24_145.cpp @@ -0,0 +1,37 @@ +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode(int x) : val(x), next(NULL) {} + * }; + */ +class Solution { +public: + ListNode* swapPairs(ListNode* head) { + if(head == NULL||head->next == NULL) + return head; + ListNode *pre = head; + ListNode *temp = pre->next; + ListNode *resHead = temp; + ListNode *link = head; + while(temp!=NULL){ + pre->next = temp->next; + temp->next = pre; + pre = pre->next; + if(pre == NULL){ + break; + } + temp = pre->next; + if(temp!=NULL){ + link->next = temp; + link = pre; + }else{ + link->next = pre; + break; + } + + } + return resHead; + } +}; \ No newline at end of file diff --git a/Week_01/id_151/LeetCode_21_151.java b/Week_01/id_151/LeetCode_21_151.java new file mode 100644 index 00000000..d1dc5487 --- /dev/null +++ b/Week_01/id_151/LeetCode_21_151.java @@ -0,0 +1,31 @@ +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode(int x) { val = x; } + * } + */ +class Solution { + public ListNode mergeTwoLists(ListNode l1, ListNode l2) { + ListNode dummyHead = new ListNode(-1); + ListNode curr = dummyHead, p = l1, q = l2; + while(p != null && q != null) { + if(p.val <= q.val) { + curr.next = p; + p = p.next; + } else { + curr.next = q; + q = q.next; + } + curr = curr.next; + } + if(p != null) { + curr.next = p; + } + if(q != null) { + curr.next = q; + } + return dummyHead.next; + } +} \ No newline at end of file diff --git a/Week_01/id_151/LeetCode_83_151.java b/Week_01/id_151/LeetCode_83_151.java new file mode 100644 index 00000000..834dddb2 --- /dev/null +++ b/Week_01/id_151/LeetCode_83_151.java @@ -0,0 +1,49 @@ +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode(int x) { val = x; } + * } + */ +class Solution { + public ListNode deleteDuplicates(ListNode head) { + ListNode ref = head; + while (ref != null && ref.next != null) { + if (ref.val == ref.next.val) { + ref.next = ref.next.next; + } else { + ref = ref.next; + } + } + return head; + + + } + + /** + * 自己的做法,略显丑陋 + * @param head + * @return + */ + public ListNode deleteDuplicates(ListNode head) { + ListNode dummyHead = new ListNode(-99999); + ListNode cur = dummyHead, p = head; + cur.next = head; + + while(p != null) { + while( p != null && cur.val == p.val) { + p = p.next; + } + if(p == null) { + cur.next = null; + } else { + cur.next = p; + cur = cur.next; + } + } + return dummyHead.next; + + + } +} \ No newline at end of file diff --git a/Week_01/id_16/LeetCode_21_16.cpp b/Week_01/id_16/LeetCode_21_16.cpp new file mode 100644 index 00000000..a76c18bc --- /dev/null +++ b/Week_01/id_16/LeetCode_21_16.cpp @@ -0,0 +1,54 @@ +/**[链表][简单] +将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。 +示例: +输入:1->2->4, 1->3->4 +输出:1->1->2->3->4->4 +*/ + +/* +个人感悟: +指针的使用要好好琢磨 +疑惑:指针当初创建出来时为了解决什么问题, +没有指针的语言是如何实现链表。 +*/ + +/* +思路1:将一个链表逐个插入另一个链表中 +*/ + +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode(int x) : val(x), next(NULL) {} + * }; + */ +class Solution { +public: + ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { + ListNode *p1 = l1, *p2 = l2; + static ListNode dummy(0); + dummy.next = p1; //将傀儡节点接入p1指针所指向的链表 + ListNode *prev = &dummy; //添加前驱指针 + //将p2指针所指向的链表元素,逐个插入p1 + //因为有傀儡节点,不用考虑头节点改变问题 + while(p1 && p2){ + if(p1->val < p2->val){ + prev = p1; + p1 = p1->next; + }else{ + prev->next = p2; + p2 = p2->next; + prev = prev->next; + prev->next = p1; + } + } + + if(p2){//将现在p2指针所指向的链表的剩余节点加入 + prev->next = p2; + } + + return dummy.next; + } +}; \ No newline at end of file diff --git a/Week_01/id_16/LeetCode_441_16.cpp b/Week_01/id_16/LeetCode_441_16.cpp new file mode 100644 index 00000000..5e1fcf7c --- /dev/null +++ b/Week_01/id_16/LeetCode_441_16.cpp @@ -0,0 +1,53 @@ +/**[二分查找][简单] +你总共有 n 枚硬币,你需要将它们摆成一个阶梯形状,第 k 行就必须正好有 k 枚硬币。 +给定一个数字 n,找出可形成完整阶梯行的总行数。 +n 是一个非负整数,并且在32位有符号整型的范围内。 +示例 1: +n = 5 +硬币可排列成以下几行: +¤ +¤ ¤ +¤ ¤ +因为第三行不完整,所以返回2. +示例 2: +n = 8 +硬币可排列成以下几行: +¤ +¤ ¤ +¤ ¤ ¤ +¤ ¤ +因为第四行不完整,所以返回3. +*/ + +/* +个人感悟: +第一种思路好想,主要考虑边界条件,第二种思路不好想,但代码简单,执行效率高。 +疑惑: +本题和二分查找有什么关系?存在利用二分查找的更好解法? +*/ + +/* +思路1:逐行累加硬币个数,总和超过给定硬币数,说明符合条件的行数为当前行数减一 +注意:总数sum的类型为long防止用例给INT_MAX为硬币数,导致int溢出 +*/ +class Solution { +public: + int arrangeCoins(int n) { + int k = 0; + long sum = 0; + while(sum <= n){ + k++; + sum += k; + } + return k-1; + } +}; +/* +思路2:从等差数列求和公式想到,将图形颠倒合并可拼成一个矩形,则k*(k+1)=2n,利用一元二次等式求解公式可得答案。 +*/ +class Solution { +public: + int arrangeCoins(int n) { + return sqrt(n*2.0 + 0.25) - 0.5; + } +}; \ No newline at end of file diff --git a/Week_01/id_16/LeetCode_50_16 .cpp b/Week_01/id_16/LeetCode_50_16 .cpp new file mode 100644 index 00000000..1921cfe7 --- /dev/null +++ b/Week_01/id_16/LeetCode_50_16 .cpp @@ -0,0 +1,69 @@ +/**[二分查找][中等] +实现 pow(x, n) ,即计算 x 的 n 次幂函数。 +示例 1: +输入: 2.00000, 10 +输出: 1024.00000 +示例 2: +输入: 2.10000, 3 +输出: 9.26100 +示例 3: +输入: 2.00000, -2 +输出: 0.25000 +解释: 2^-2 = 1/2^2 = 1/4 = 0.25 +说明: +-100.0 < x < 100.0 +n 是 32 位有符号整数,其数值范围是 [−2^31, 2^31 − 1] 。 +*/ + +/* +个人感悟: +第一种思路好想,但是执行效率不好, +思路2与思路3思想差不多,思路2需要考虑边界条件,思路3巧妙的避开了。 +对于用递归还是用for循环还是要多多练习! +要充分考虑数据范围及边界条件。 +*/ + +/*未通过:超时 +思路1:for循环累乘 +结果:超出时间限制 +*/ + +/*未通过:执行错误 +思路2:用递归实现,x^n = (x^(n/2))^2 +测试用例: +1.00000 +-2147483648 +*/ +class Solution { +public: + double myPow(double x, int n) { + if(n == 0) return 1; + if(n == 1) return x; + if(n < 0) return (1 / myPow(x, -n)); //negation of -2147483648 cannot be represented in type 'int' + double res; + if(n % 2 == 0){ + res = myPow(x, n/2); + res *= res; + }else{ + res = myPow(x, (n-1)/2); + res = res*res*x; + } + return res; + } +}; + +/*通过 +思路3:用for循环实现,x^n = (x^2)^(n/2) +注意:代码中i=1时刻需要注意 +*/ +class Solution { +public: + double myPow(double x, int n) { + double res = 1.0; + for(int i = n; i != 0; i /= 2){ + if(i % 2 != 0) res *= x; + x *= x; + } + return n > 0 ? res : 1/res; + } +}; \ No newline at end of file diff --git a/Week_01/id_16/LeetCode_83_16.cpp b/Week_01/id_16/LeetCode_83_16.cpp new file mode 100644 index 00000000..46df44dc --- /dev/null +++ b/Week_01/id_16/LeetCode_83_16.cpp @@ -0,0 +1,42 @@ +/**[链表][简单] +给定一个排序链表,删除所有重复的元素,使得每个元素只出现一次。 +示例 1: +输入: 1->1->2 +输出: 1->2 +示例 2: +输入: 1->1->2->3->3 +输出: 1->2->3 +*/ + +/* +个人感悟: +指针的使用要好好琢磨 +*/ + +/* +思路1:由于输入的列表已排序,因此我们可以通过将结点的值与它之后的结点进行比较来确定它是否为重复结点。 +如果它是重复的,我们更改当前结点的 next 指针,以便它跳过下一个结点并直接指向下一个结点之后的结点。 +*/ + +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode(int x) : val(x), next(NULL) {} + * }; + */ +class Solution { +public: + ListNode* deleteDuplicates(ListNode* head) { + ListNode* current = head; + while(current && current->next){ + if(current->val == current->next->val){ + current->next = current->next->next; + }else{ + current = current->next; + } + } + return head; + } +}; \ No newline at end of file diff --git a/Week_01/id_17/LeetCode_20_17.swift b/Week_01/id_17/LeetCode_20_17.swift new file mode 100644 index 00000000..ed445faa --- /dev/null +++ b/Week_01/id_17/LeetCode_20_17.swift @@ -0,0 +1,66 @@ +class Solution { + func isValid(_ s: String) -> Bool { + var stack1 = Stack(Array(s)) + var stack2 = Stack([Character]()) + + while !stack1.isEmpty { + let a = stack1.pop()! + if let b = stack2.peek() { + if map(a) > 0 && map(a)+map(b) == 0 { + stack2.pop() + } else { + stack2.push(a) + } + } else { + stack2.push(a) + } + } + + if stack2.isEmpty { + return true + } else { + return false + } + } + + func map(_ character: Character) -> Int { + switch character { + case "(": return 1 + case ")": return -1 + case "{": return 2 + case "}": return -2 + case "[": return 4 + case "]": return -4 + default: return 0 + } + } +} + +struct Stack { + + private var storage: [Element] = [] + + public init(_ elements: [Element]) { + storage = elements + } + + public mutating func push(_ element: Element) { + storage.append(element) + } + + @discardableResult + public mutating func pop() -> Element? { + return storage.popLast() + } + + func peek() -> Element? { + return storage.last + } + + public var isEmpty: Bool { + return peek() == nil + } +} + +// Runtime: 12 ms, faster than 52.39% of Swift online submissions for Valid Parentheses. +// Memory Usage: 19.7 MB, less than 12.25% of Swift online submissions for Valid Parentheses. \ No newline at end of file diff --git a/Week_01/id_17/LeetCode_33_17.swift b/Week_01/id_17/LeetCode_33_17.swift new file mode 100644 index 00000000..5b818e90 --- /dev/null +++ b/Week_01/id_17/LeetCode_33_17.swift @@ -0,0 +1,46 @@ +class Solution { + func search(_ nums: [Int], _ target: Int) -> Int { + if nums.count == 0 { return -1 } + let breakPoint = find_breakPoint(nums) + return binary_search(nums, target, offset: breakPoint) + } + + func find_breakPoint(_ numbers: [Int]) -> Int { + for (index, number) in numbers.enumerated() { + if number < numbers[0] { return index } + } + return 0 + } + + func binary_search(_ numbers: [Int], _ target: Int, offset: Int) -> Int { + if numbers.count == 0 { return -1 } + var low = 0 + var high = numbers.count - 1 + + while low <= high { + let middle = (low + high)/2 + let index = realIndex(middle, count: numbers.count, offset: offset) + let number = numbers[index] + if number == target { + return index + } else if number < target { + low = middle + 1 + } else { + high = middle - 1 + } + } + + return -1 + } + + func realIndex(_ index: Int, count: Int, offset: Int) -> Int { + if index < count-offset { + return index+offset + } else { + return index+offset-count + } + } +} + +// Runtime: 20 ms, faster than 100.00% of Swift online submissions for Search in Rotated Sorted Array. +// Memory Usage: 19 MB, less than 33.33% of Swift online submissions for Search in Rotated Sorted Array. diff --git a/Week_01/id_17/LeetCode_905_17.js b/Week_01/id_17/LeetCode_905_17.js new file mode 100644 index 00000000..a3d4a646 --- /dev/null +++ b/Week_01/id_17/LeetCode_905_17.js @@ -0,0 +1,11 @@ +var sortArrayByParity = function(A) { + for (var i=0, j=A.length-1; i=j) break; else i++; + while (A[j]%2 == 1) if (i>=j) break; else j--; + [A[i], A[j]] = [A[j], A[i]]; + } + return A; +}; + +// Runtime: 84 ms, faster than 93.15% of JavaScript online submissions for Sort Array By Parity. +// Memory Usage: 37.3 MB, less than 40.08% of JavaScript online submissions for Sort Array By Parity. \ No newline at end of file diff --git a/Week_01/id_17/LeetCode_905_17.swift b/Week_01/id_17/LeetCode_905_17.swift new file mode 100644 index 00000000..11f564c6 --- /dev/null +++ b/Week_01/id_17/LeetCode_905_17.swift @@ -0,0 +1,21 @@ +class Solution { + func sortArrayByParity(_ A: [Int]) -> [Int] { + var even = [Int]() + var odd = [Int]() + + for number in A { + if number % 2 == 0 { + even.append(number) + } else { + odd.append(number) + } + } + + return even+odd + } +} + +// 使用注释中的 forEach 代码的运行时间是 92 ms +// 而使用 for in 的运行时间只有 72 ms +// Runtime: 72 ms, faster than 93.41% of Swift online submissions for Sort Array By Parity. +// Memory Usage: 19.4 MB, less than 12.50% of Swift online submissions for Sort Array By Parity. diff --git a/Week_01/id_17/LeetCode_922_17.js b/Week_01/id_17/LeetCode_922_17.js new file mode 100644 index 00000000..ef2fa661 --- /dev/null +++ b/Week_01/id_17/LeetCode_922_17.js @@ -0,0 +1,12 @@ +var sortArrayByParityII = function(A) { + var j = 1; + for (var i=0, j=1; i [Int] { + var result = A + var evenIndex = 0 + var oddIndex = 1 + + for index in 0.. ts = new Stack(); + Dictionary dic = new Dictionary(); + dic.Add(')', '('); + dic.Add('}', '{'); + dic.Add(']', '['); + foreach (var item in s) + { + if (dic.ContainsKey(item)) + { + if (ts.Count <= 0) + { + return false; + } + + var left = ts.Pop(); + if (left != dic[item]) + { + return false; + } + } + else + { + ts.Push(item); + } + } + + if (ts.Count > 0) + { + return false; + } + else + { + return true; + } + } + } +} diff --git a/Week_01/id_2/LeetCode_21_2.cs b/Week_01/id_2/LeetCode_21_2.cs new file mode 100644 index 00000000..3c8899ec --- /dev/null +++ b/Week_01/id_2/LeetCode_21_2.cs @@ -0,0 +1,50 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace leetcode.合并两个有序链表 +{ + public class ListNode + { + public int val; + public ListNode next; + public ListNode(int x) { val = x; } + } + + public class 合并两个有序链表 + { + public ListNode MergeTwoLists(ListNode l1, ListNode l2) + { + ListNode head = new ListNode(int.MinValue); + ListNode tail = head; + while (l1 != null && l2 != null) + { + if (l1.val < l2.val) + { + tail.next = l1; + l1 = l1.next; + } + else + { + tail.next = l2; + l2 = l2.next; + } + tail = tail.next; + } + + if (l1 != null) + { + tail.next = l1; + } + + if (l2 != null) + { + tail.next = l2; + } + head = head.next; + return head; + } + } +} diff --git a/Week_01/id_2/LeetCode_242_2.cs b/Week_01/id_2/LeetCode_242_2.cs new file mode 100644 index 00000000..7aa1f7cb --- /dev/null +++ b/Week_01/id_2/LeetCode_242_2.cs @@ -0,0 +1,41 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace leetcode +{ + class _242_有效的字母异位词 + { + public bool IsAnagram(string s, string t) + { + if ((s == string.Empty && t == string.Empty) || s == t) + { + return true; + } + + int[] a = new int[26]; + for (int i = 0; i < s.Length; i++) + { + a[s[i] - 'a']++; + } + + for (int i = 0; i < t.Length; i++) + { + a[t[i] - 'a']--; + } + + for (int i = 0; i < a.Length; i++) + { + if (a[i] != 0) + { + return false; + } + } + + return true; + } + } +} diff --git a/Week_01/id_2/LeetCode_24_2.cs b/Week_01/id_2/LeetCode_24_2.cs new file mode 100644 index 00000000..feeb3f4a --- /dev/null +++ b/Week_01/id_2/LeetCode_24_2.cs @@ -0,0 +1,55 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace leetcode.两两交换链表中的节点 +{ + + public class ListNode + { + public int val; + public ListNode next; + public ListNode(int x) { val = x; } + } + + public class 两两交换链表中的节点 + { + public ListNode SwapPairs(ListNode head) + { + ListNode a = new ListNode(int.MinValue); + ListNode b = head; + ListNode c = head?.next; + a.next = head; + head = a; + + while (b != null && c != null) + { + var temp = c.next; + c.next = b; + b.next = temp; + a.next = c; + a = b; + b = b?.next; + c = b?.next; + } + head = head.next; + + return head; + } + + public ListNode SwapPairs_recursive(ListNode head) + { + if (head == null || head.next == null) + { + return head; + } + + var next = head.next; + head.next = SwapPairs_recursive(next.next); + next.next = head; + return next; + } + } +} diff --git a/Week_01/id_2/LeetCode_503_2.cs b/Week_01/id_2/LeetCode_503_2.cs new file mode 100644 index 00000000..8f4da2b9 --- /dev/null +++ b/Week_01/id_2/LeetCode_503_2.cs @@ -0,0 +1,31 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace leetcode +{ + public class 下一个更大元素_II + { + public int[] NextGreaterElements(int[] nums) + { + int[] result = new int[nums.Length]; + for (int i = 0; i < nums.Length; i++) + { + result[i] = -1; + for (int j = 1; j < nums.Length; j++) + { + var index = (i + j) % nums.Length; + if (nums[index] > nums[i]) + { + result[i] = nums[index]; + break; + } + } + } + + return result; + } + } +} diff --git a/Week_01/id_2/LeetCode_687_2.cs b/Week_01/id_2/LeetCode_687_2.cs new file mode 100644 index 00000000..c0d6ff69 --- /dev/null +++ b/Week_01/id_2/LeetCode_687_2.cs @@ -0,0 +1,58 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace leetcode +{ + public class 最长同值路径 + { + public class TreeNode + { + public int val; + public TreeNode left; + public TreeNode right; + public TreeNode(int x) { val = x; } + } + + int max = 0; + + public int LongestUnivaluePath(TreeNode root) + { + F(root); + return max; + } + + int F(TreeNode root) + { + if (root == null) + { + return 0; + } + + int left = F(root.left); + int right = F(root.right); + if (root.val == root?.left?.val) + { + left++; + } + else + { + left = 0; + } + + if (root.val == root?.right?.val) + { + right++; + } + else + { + right = 0; + } + + max = Math.Max(left + right, max); + return Math.Max(left, right); + } + } +} diff --git a/Week_01/id_2/LeetCode_83_2.cs b/Week_01/id_2/LeetCode_83_2.cs new file mode 100644 index 00000000..3d5b302c --- /dev/null +++ b/Week_01/id_2/LeetCode_83_2.cs @@ -0,0 +1,68 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace leetcode +{ + + public class ListNode + { + public int val; + public ListNode next; + public ListNode(int x) { val = x; } + } + + public class 删除排序链表中的重复元素 + { + public ListNode DeleteDuplicates(ListNode head) + { + if (head == null) + { + return null; + } + + if (head.next == null) + { + return head; + } + + if (head.val == head.next.val) + { + head.next = head.next.next; + DeleteDuplicates(head); + } + else + { + DeleteDuplicates(head.next); + } + + return head; + } + + public ListNode DeleteDuplicates_recursive(ListNode head) + { + if (head == null) + { + return null; + } + + + ListNode currentNode = head; + while (currentNode.next != null) + { + if (currentNode.val == currentNode.next.val) + { + currentNode.next = currentNode.next.next; + } + else + { + currentNode = currentNode.next; + } + } + + return head; + } + } +} diff --git a/Week_01/id_2/LeetCode_905_2.cs b/Week_01/id_2/LeetCode_905_2.cs new file mode 100644 index 00000000..11cd7da8 --- /dev/null +++ b/Week_01/id_2/LeetCode_905_2.cs @@ -0,0 +1,40 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace leetcode +{ + public class 按奇偶排序数组 + { + public int[] SortArrayByParity(int[] A) + { + int[] o = new int[A.Count()]; + int[] e = new int[A.Count()]; + int p = 0; + int q = 0; + for (int i = 0; i < A.Count(); i++) + { + if (A[i] % 2 == 1) + { + o[p] = A[i]; + p++; + } + else + { + e[q] = A[i]; + q++; + } + } + + for (int i = 0; i < p; i++) + { + e[q] = o[i]; + q++; + } + + return e; + } + } +} diff --git a/Week_01/id_2/LeetCode_922_2.cs b/Week_01/id_2/LeetCode_922_2.cs new file mode 100644 index 00000000..f739f995 --- /dev/null +++ b/Week_01/id_2/LeetCode_922_2.cs @@ -0,0 +1,32 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace leetcode +{ + public class 按奇偶排序数组_II + { + public int[] SortArrayByParityII(int[] A) + { + int[] o = new int[A.Length]; + int p = 0; + int q = 1; + for (int i = 0; i < A.Length; i++) + { + if (A[i] % 2 == 0) + { + o[p] = A[i]; + p += 2; + } + else + { + o[q] = A[i]; + q += 2; + } + } + return o; + } + } +} diff --git a/Week_01/id_21/LeetCode_020_021.cpp b/Week_01/id_21/LeetCode_020_021.cpp new file mode 100644 index 00000000..adef7452 --- /dev/null +++ b/Week_01/id_21/LeetCode_020_021.cpp @@ -0,0 +1,22 @@ +class Solution { +public: + bool isValid(string s) { + stack temp; + for (int i = 0; i < s.size(); i++) { + if (s.size() > 0 && isPair(temp.top(), s[i])) { + temp.pop(); + } else { + temp.push(s[i]); + } + } + return temp.size() == 0; + } + +private: + bool isPair(char left, char right) { + if (left == '(' && right == ')') return true; + if (left == '[' && right == ']') return true; + if (left == '{' && right == '}') return true; + return false; + } +}; \ No newline at end of file diff --git a/Week_01/id_21/LeetCode_021_021.cpp b/Week_01/id_21/LeetCode_021_021.cpp new file mode 100644 index 00000000..3aa8f6b8 --- /dev/null +++ b/Week_01/id_21/LeetCode_021_021.cpp @@ -0,0 +1,33 @@ +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode(int x) : val(x), next(NULL) {} + * }; + */ +class Solution { +public: + ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { + if (l1 == nullptr) return l2; + if (l2 == nullptr) return l1; + ListNode* dummy = new ListNode(0); + ListNode* p = dummy; + while(l1 != nullptr && l2 != nullptr) { + if (l1->val <= l2->val) { + p->next = l1; + l1 = l1->next; + } else { + p->next = l2; + l2 = l2->next; + } + p = p->next; + } + if (l1 != nullptr) p->next = l1; + else p->next = l2; + + p = dummy->next; + delete dummy; + return p; + } +}; \ No newline at end of file diff --git a/Week_01/id_21/LeetCode_024_021.cpp b/Week_01/id_21/LeetCode_024_021.cpp new file mode 100644 index 00000000..1a8d3b6d --- /dev/null +++ b/Week_01/id_21/LeetCode_024_021.cpp @@ -0,0 +1,33 @@ +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode(int x) : val(x), next(NULL) {} + * }; + */ +class Solution { +public: + ListNode* swapPairs(ListNode* head) { + if (head == nullptr || head->next == nullptr) return head; + ListNode* dummy = new ListNode(0); + dummy->next = head; + + ListNode * prev = dummy, * p1, * p2, * next; + while(prev->next && prev->next->next) { + p1 = prev->next; + p2 = p1->next; + next = p2->next; + + prev->next = p2; + p2->next = p1; + p1->next = next; + prev = p1; + } + + p1 = dummy->next; + delete dummy; + + return p1; + } +}; \ No newline at end of file diff --git a/Week_01/id_21/LeetCode_025_021.cpp b/Week_01/id_21/LeetCode_025_021.cpp new file mode 100644 index 00000000..c1fa10e1 --- /dev/null +++ b/Week_01/id_21/LeetCode_025_021.cpp @@ -0,0 +1,55 @@ +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode(int x) : val(x), next(NULL) {} + * }; + */ +class Solution { +public: + ListNode* reverseKGroup(ListNode* head, int k) { + if (head == nullptr || k == 1) return head; + ListNode* dummy = new ListNode(0); + dummy->next = head; + + ListNode* begin = dummy, *end, * next; + + while(begin != nullptr) { + int i; + end = begin->next; + for(i = 1; i < k; i++) { + if (end == nullptr || end->next == nullptr) break; + end = end->next; + } + if (i < k) break; + next = begin->next; + reverse(begin, end); + begin = next; + } + + return dummy->next; + } + + /* + * 此函数为左开右闭区间 + * 直接修改 begin->next 的指向来完成翻转 + */ + void reverse(ListNode* begin, ListNode* end) { + end = end->next; + ListNode* p1 = begin->next, * next; + + ListNode* dummy = new ListNode(0); + dummy->next = end; + + while (p1 != end) { + next = p1->next; + p1->next = dummy->next; + dummy->next = p1; + p1 = next; + } + + begin->next = dummy->next; + delete dummy; + } +}; \ No newline at end of file diff --git a/Week_01/id_21/LeetCode_081_021.cpp b/Week_01/id_21/LeetCode_081_021.cpp new file mode 100644 index 00000000..e6df66fa --- /dev/null +++ b/Week_01/id_21/LeetCode_081_021.cpp @@ -0,0 +1,43 @@ +/* + * BF: 直接遍历,算法复杂度 O(N) + */ +class Solution { +public: + bool search(vector& nums, int target) { + for(auto itr = nums.begin(); itr != nums.end(); itr++) { + if (*itr == target) return true; + } + return false; + } +}; + +/* + * 二分法查找 + */ +class Solution { +public: + bool search(vector& nums, int target) { + if (nums.size() < 1) return false; + if (nums.size() == 1) return nums[0] == target; + // 前半段,顺序查找 target + // 如果没有找到 target ,但是找到反转的位置,则停止顺序查找 + int begin = 0; + while (begin + 1 < nums.size()) { + if (nums[begin] == target || nums[begin + 1] == target) return true; + if (nums[begin] > nums[begin + 1]) break; + begin++; + } + + // 后半段使用二分法查找 + int end = nums.size(); + while (begin + 1 < end && end <= nums.size()) { + int pos = (begin + end) / 2; + if (nums[pos] == target) return true; + if (begin == end) break; + if (nums[pos] < target) begin = pos; + else end = pos; + } + + return false; + } +}; \ No newline at end of file diff --git a/Week_01/id_21/LeetCode_083_021.cpp b/Week_01/id_21/LeetCode_083_021.cpp new file mode 100644 index 00000000..8a083192 --- /dev/null +++ b/Week_01/id_21/LeetCode_083_021.cpp @@ -0,0 +1,25 @@ +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode(int x) : val(x), next(NULL) {} + * }; + */ +class Solution { +public: + ListNode* deleteDuplicates(ListNode* head) { + if (head == nullptr || head->next == nullptr) return head; + ListNode* p1 = head, * temp; + while (p1->next != nullptr) { + if (p1->val == p1->next->val) { + temp = p1->next; + p1->next = p1->next->next; + delete temp; + } else { + p1 = p1->next; + } + } + return head; + } +}; \ No newline at end of file diff --git a/Week_01/id_21/LeetCode_142_021.cpp b/Week_01/id_21/LeetCode_142_021.cpp new file mode 100644 index 00000000..7a56e5e1 --- /dev/null +++ b/Week_01/id_21/LeetCode_142_021.cpp @@ -0,0 +1,64 @@ +/** + * 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) { + set path; + set::iterator itr; + + ListNode* p1 = head; + while(p1 != nullptr) { + itr = path.find(p1); + if (itr != path.end()) { + return *itr; + } + path.insert(p1); + p1 = p1->next; + } + + return NULL; + } +}; + +/** + * 快慢指针做法 + */ +/** + * 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) { + if (head == NULL || head->next == NULL) + return NULL; + + ListNode* fast = head; + ListNode* slow = head; + + while(fast->next && fast->next->next) { + slow = slow->next; + fast = fast->next->next; + if (slow == fast) { + fast = head; + while(slow != fast) { + slow = slow->next; + fast = fast->next; + } + return fast; + } + } + + return NULL; + } +}; \ No newline at end of file diff --git a/Week_01/id_21/LeetCode_153_021.cpp b/Week_01/id_21/LeetCode_153_021.cpp new file mode 100644 index 00000000..b5121bb9 --- /dev/null +++ b/Week_01/id_21/LeetCode_153_021.cpp @@ -0,0 +1,47 @@ +class Solution { +public: + int findMin(vector& nums) { + for(int i = 1; i < nums.size(); i ++) { + if (nums[i] < nums[i-1]) return nums[i]; + } + return nums[0]; + } +}; + +/* + * 二分法查找 + */ +class Solution { +public: + int findMin(vector& nums) { + if(nums.size() == 1) { + return nums[0]; + } + + int left = 0, right = nums.size() - 1; + + if (nums[right] > nums[0]) { + return nums[0]; + } + + while (right >= left) { + int mid = left + (right - left) / 2; + + if (nums[mid] > nums[mid + 1]) { + return nums[mid + 1]; + } + + if (nums[mid - 1] > nums[mid]) { + return nums[mid]; + } + + if (nums[mid] > nums[0]) { + left = mid + 1; + } else { + right = mid - 1; + } + } + + return -1; + } +}; diff --git a/Week_01/id_21/LeetCode_503_021.cpp b/Week_01/id_21/LeetCode_503_021.cpp new file mode 100644 index 00000000..2895587e --- /dev/null +++ b/Week_01/id_21/LeetCode_503_021.cpp @@ -0,0 +1,36 @@ +// 暴力破解方法 +class Solution { +public: + vector nextGreaterElements(vector& nums) { + vector result; + + if (nums.size() == 1) { + result.push_back(-1); + return result; + } + + int i, j; + for(i = 0; i < nums.size(); i ++) { + + if(i == nums.size() - 1) { + j = 0; + } else { + j = i + 1; + } + while(j != i) { + if (nums[j] > nums[i]) { + result.push_back(nums[j]); + break; + } + if (j == nums.size() - 1) { + j = 0; + } else { + j++; + } + + } + if (i == j) result.push_back(-1); + } + return result; + } +}; \ No newline at end of file diff --git a/Week_01/id_21/LeetCode_905_021.cpp b/Week_01/id_21/LeetCode_905_021.cpp new file mode 100644 index 00000000..db8841f9 --- /dev/null +++ b/Week_01/id_21/LeetCode_905_021.cpp @@ -0,0 +1,26 @@ +class Solution { +public: + vector sortArrayByParity(vector& A) { + int i = 0, j = A.size() - 1; + while (i < j) { + if (isOdd(A[i]) && isEven(A[j])) { + swap(A[i], A[j]); + i++; + j--; + } else if (isEven(A[i])) { + i++; + } else if (isOdd(A[j])) { + j--; + } + } + return A; + } +private: + inline bool isOdd(int value) { + return value % 2; + } + + inline bool isEven(int value) { + return !isOdd(value); + } +}; \ No newline at end of file diff --git a/Week_01/id_21/LeetCode_922_021.cpp b/Week_01/id_21/LeetCode_922_021.cpp new file mode 100644 index 00000000..1d72d201 --- /dev/null +++ b/Week_01/id_21/LeetCode_922_021.cpp @@ -0,0 +1,27 @@ +class Solution { +public: + vector sortArrayByParityII(vector& A) { + if (A.size() == 1) return A; + int i = 0, j = 1; + while(j < A.size() && i < A.size() - 1) { + if (isOdd(A[i]) && isEven(A[j])) { + swap(A[i], A[j]); + i += 2; + j += 2; + } else if (isEven(A[i])) { + i += 2; + } else if (isOdd(A[j])) { + j += 2; + } + } + return A; + } +private: + inline bool isOdd(int value) { + return value % 2; + } + + inline bool isEven(int value) { + return !isOdd(value); + } +}; \ No newline at end of file diff --git a/Week_01/id_24/Leetcode_242_024.rb b/Week_01/id_24/Leetcode_242_024.rb new file mode 100644 index 00000000..4a66d52d --- /dev/null +++ b/Week_01/id_24/Leetcode_242_024.rb @@ -0,0 +1,40 @@ +# 解法一 +def is_anagram(s, t) + source_hash = {} + s.each_char { |s| + if source_hash[s] + source_hash[s] += 1 + else + source_hash[s] = 1 + end + } + t.each_char { |t| + return false unless source_hash.keys.include? t + source_hash[t] -= 1 + source_hash.delete_if {|_, value| value == 0 } + } + return true if source_hash.empty? + return false +end +#解法二 +def is_anagram(s, t) + x = Array.new(26, 0) + for i in 0..s.length-1 do + value = s[i].ord - 97 + x[value] ? x[value] += 1 : x[value] = 0 + end + for j in 0..t.length-1 do + value = t[j].ord - 97 + return false if x[value] == 0 + x[value] -= 1 + end + return true if x.sum == 0 + return false +end + +# 解法三 +def is_anagram(s, t) + s_sort = s.split("").sort + t_sort = t.split("").sort + s_sort == t_sort +end diff --git a/Week_01/id_24/NOTE.md b/Week_01/id_24/NOTE.md index c684e62f..4adb8d6b 100644 --- a/Week_01/id_24/NOTE.md +++ b/Week_01/id_24/NOTE.md @@ -1 +1,22 @@ -# 学习笔记 \ No newline at end of file +# 学习笔记 + +242.有效字母异位词 +首先需要确定题目的描述有效字母异位词的含义 +刚开始结合例子的理解是字母按顺序交换,1和2换位,3和4换位,依次类推 +在这个思路下想的是首先我遍历原串按照次序存储字母,遍历目标串依次交换对比刚才的存储顺序。 +后来看评论才理解,易位词指的是相同数量和种类的字母的不同排列,次序不一定是1和2互换,3和4互换,相对来说更简单了,所以我们理解题目 +含义很重要,需要先理解题目在去做题。 +下面是思路: +1.首先遍历原串s, 把字母存到哈希表source_hash里面,key是字母,value是出现次数 +2.遍历目标串t,依次查寻目标串的字母是否出现在source_hash中,如果没出现直接返回false,如果找到了,将其对应的值将其减一,清楚哈希表中值为空的数据 +3.遍历完成之后,检查source_hash是否为空,为空说明字符种类和数量一致返回true,不为空返回false。 +优化 +将哈希表转化为数组,字母的ascll码做下标,出现字数作为数组元素,进一步优化。 + +83. 删除排序链表中的重复元素 +该问题比较简单,因为链表已经排序,只需要顺序检查next节点的值是否等于当前节点的值,如果相等,删除next节点,移动指针到next节点的next节点,需要注意的问题是注意链表的边界条件,头结点和尾节点的问题。 +看到一个好的方法是使用递归的方案去解决删除重复节点的思路。 + +687. 最长同值路径 +该问题想到用递归去求解,但是实际递归代码实现有问题,还需要进一步优化。 + diff --git a/Week_01/id_24/leet_code.md b/Week_01/id_24/leet_code.md new file mode 100644 index 00000000..9f17a78d --- /dev/null +++ b/Week_01/id_24/leet_code.md @@ -0,0 +1,89 @@ +### LeetCode + 题目: [83. Remove Duplicates from Sorted List](https://leetcode-cn.com/problems/remove-duplicates-from-sorted-list/) + + 解题: + +```ruby +# 常规思路 +# 注意边界条件 +def delete_duplicates(head) + if head.nil? || head.next.nil? + return head + end + current = head + while !current.nil? && !current.next.nil? do + if current.val == current.next.val + current.next = current.next.next + else + current = current.next + end + end + return head +end + +# 递归删除 +def delete_duplicates(head) + if head.nil? || head.next.nil? + return head + end + + head.next = delete_duplicates(head.next) + if head.val == head.next.val + head = head.next + end + return head +end +``` + +### LeetCode + 题目: [242. Valid Anagram](https://leetcode-cn.com/problems/valid-anagram/) + + 解题: + 1.常规思路遍历字符串S,存储到哈希表中,遍历字符串t,依次查找哈希表中是否有该字母元素, + 哈希表中元素值为0时,删除该元素,最后判读哈希表是否为空 + 2.优化思路,不使用编程语言自己的哈希表,使用自己构建的数组存储字母元素,优化执行效率 + 3.看到别人的解法觉得很好,把两个字符串进行排列,比较两个字符串是否相同 + +```ruby +# 解法一 +def is_anagram(s, t) + source_hash = {} + s.each_char { |s| + if source_hash[s] + source_hash[s] += 1 + else + source_hash[s] = 1 + end + } + t.each_char { |t| + return false unless source_hash.keys.include? t + source_hash[t] -= 1 + source_hash.delete_if {|_, value| value == 0 } + } + return true if source_hash.empty? + return false +end + +#解法二 +def is_anagram(s, t) + x = Array.new(26, 0) + for i in 0..s.length-1 do + value = s[i].ord - 97 + x[value] ? x[value] += 1 : x[value] = 0 + end + for j in 0..t.length-1 do + value = t[j].ord - 97 + return false if x[value] == 0 + x[value] -= 1 + end + return true if x.sum == 0 + return false +end + +# 解法三 +def is_anagram(s, t) + s_sort = s.split("").sort + t_sort = t.split("").sort + s_sort == t_sort +end +``` diff --git a/Week_01/id_24/leetcode_687_024.rb b/Week_01/id_24/leetcode_687_024.rb new file mode 100644 index 00000000..8856c55d --- /dev/null +++ b/Week_01/id_24/leetcode_687_024.rb @@ -0,0 +1,33 @@ +# Definition for a binary tree node. +# class TreeNode +# attr_accessor :val, :left, :right +# def initialize(val) +# @val = val +# @left, @right = nil, nil +# end +# end + +# @param {TreeNode} root +# @return {Integer} +def longest_univalue_path(root) + path_length = 0 + + get_path_length(root) + + return path_length +end + +def get_path_length(root) + return 0 if root.nil? + left_path_length = get_path_length(root.left) + right_path_length = get_path_length(root.right) + left_length, right_length = 0, 0 + + if !root.left.nil? && root.left.val == root.val + left_length = left_path_length + 1 + elsif !root.right.nil? && root.right.val == root.val + right_length = right_path_length + 1 + end + path_length = [path_length, (left_length + right_length)].max + return [left_length, right_length].max +end diff --git a/Week_01/id_24/leetcode_83_024.rb b/Week_01/id_24/leetcode_83_024.rb new file mode 100644 index 00000000..4e941de4 --- /dev/null +++ b/Week_01/id_24/leetcode_83_024.rb @@ -0,0 +1,28 @@ +# 递归删除 +def delete_duplicates(head) + if head.nil? || head.next.nil? + return head + end + + head.next = delete_duplicates(head.next) + if head.val == head.next.val + head = head.next + end + return head +end +# 常规思路 +# 注意边界条件 +def delete_duplicates(head) + if head.nil? || head.next.nil? + return head + end + current = head + while !current.nil? && !current.next.nil? do + if current.val == current.next.val + current.next = current.next.next + else + current = current.next + end + end + return head +end diff --git a/Week_01/id_25/LeetCode_441_025.rb b/Week_01/id_25/LeetCode_441_025.rb new file mode 100644 index 00000000..53ae348c --- /dev/null +++ b/Week_01/id_25/LeetCode_441_025.rb @@ -0,0 +1,23 @@ +# @param {Integer} n +# @return {Integer} +def arrange_coins(n) + low = 0 + high = n + loop do + k = ((low+high)/2).ceil + if k * (k + 1)/2 == n + return k + break + elsif k * (k + 1)/2 > n && (k -1) * k / 2 < n + return k - 1 + break + elsif low > high + return -1 + break + elsif k * (k + 1)/2 > n + high = k - 1 + else k * (k + 1)/2 < n + low = k + 1 + end + end +end diff --git a/Week_01/id_25/LeetCode_905_025.rb b/Week_01/id_25/LeetCode_905_025.rb new file mode 100644 index 00000000..ca31fda4 --- /dev/null +++ b/Week_01/id_25/LeetCode_905_025.rb @@ -0,0 +1,18 @@ +# @param {Integer[]} a +# @return {Integer[]} +def sort_array_by_parity(a) + if a.length < 2 + return a + end + + left = [] + right = [] + a.length.times.each do + if a[0].even? + left << a.delete_at(0) + else + right << a.delete_at(0) + end + end + a = left + right +end diff --git a/Week_01/id_25/NOTE.md b/Week_01/id_25/NOTE.md index c684e62f..ae13e934 100644 --- a/Week_01/id_25/NOTE.md +++ b/Week_01/id_25/NOTE.md @@ -1 +1,117 @@ -# 学习笔记 \ No newline at end of file +# 学习笔记 + +## 二分查找 + +### 第一次写的没写对的 +```ruby +def binary_search(array = [], term) + low = 0 + high = array.length + mid = (low + high)/2.ceil + + if term > array[mid] # term偏大 + low = mid + 1 + elsif term < array[mid] # term 偏小 + high = mid -1 + elsif term == array[mid] + return mid + else + return "数组中没有此元素" + end +end +``` + +### 考虑边界条件后写对的 +```ruby +# 二分法 +def binary_search(array, term) + low = 0 + high = array.length - 1 + + loop do + mid = (low + high)/2.ceil + + if term > array[mid] # term偏大 + low = mid + 1 + end + if term < array[mid] # term偏小 + high = mid - 1 + end + + # 循环结束条件 + # 1. 找到 term, 跳出循环 + # 2. 数组遍历完了,跳出循环 + + if term == array[mid] + return mid + end + if low > high + return "数组中没有此元素" + end + end +end + +### 测试 +```ruby +a = [1,2,3,4,5], +b = [3, 6, 9, 29, 38, 42] +binary_search(a, 2) +# `=> 1` +binary_search(b, 29) +# `=> 3` +binary_search(b, 22) +# `=> "数组中没有此元素"` +``` + +你总共有 n 枚硬币,你需要将它们摆成一个阶梯形状,第 k 行就必须正好有 k 枚硬币。 +给定一个数字 n,找出可形成完整阶梯行的总行数。 +n 是一个非负整数,并且在32位有符号整型的范围内。 + +审题:n 是一个非负整数,并且在32位有符号整型的范围内。 得出 n <= 2^31 即2147483648 + +分析:什么时候返回k? 边界条件 +条件1: (1+k)/2 * k = n +条件2: (1+k)/2 * k > n && [1 + (k-1)]/2 * (k-1) < n +k的值 从(1..n) 里面一个一个试, 直到找到符合条件1和2的 k值,并返回。 +继续分析:k的值 从(1..n) 里面一个一个试太麻烦,(1..n)是一个数组,可以试试用二分法。 + +```ruby +def binary_coin(n) + + array = (1..n).to_a # 范围转换数组花费时间比较长 + + low = 0 + high = array.length - 1 + + loop do + mid = (low+ high)/2.ceil + k = array[mid] + if (1+ k) * k / 2 == n # 边界条件1 + return @result = k + elsif (1+ k) * k / 2 > n && k * (k-1)/2 < n # 边界条件2 + return @result = k - 1 + elsif(1+ k) * k / 2 > n # mid偏大 + high = mid - 1 + else # mid偏小 + low = mid + 1 + end + end +end + +(1..10).to_a.each do |x| + puts binary_coin(x) +end +puts 'binary_coin(100000000)' +puts binary_coin(100000000) +``` + +## 我理解的练习的过程是纠正思维的过程 +>刚开始做这个算法的时候,我看见这个题目是关于在二分查找的题。所以我就在想怎么使用二分查找,二分查找有什么特点,反正就是使劲往二分查找上面套,看了半天越来越发现,这他么哪里是二分查找,倒有点像递归。 +反正连想带画了几十分钟没弄出来,还跑了点歪路,去想用数学怎么去解。 +我发觉这种思维方式有问题 + +拿到一个算法,第一步思考的不应该是去套什么公式,而是向正常思维一样。先用几个很简单的例子来看看这个算法的过程。 +然后我再一步一步解决。在演化的过程中,我觉得把数据一个一个带进去试很烦,而这个正是计算机擅长的事情。 + + +### 有一个新的思路,二分法可以试试递归,因为每次操作都是和中间的数进行比较 diff --git a/Week_01/id_26/Leetcode_441_26.java b/Week_01/id_26/Leetcode_441_26.java new file mode 100644 index 00000000..f780d827 --- /dev/null +++ b/Week_01/id_26/Leetcode_441_26.java @@ -0,0 +1,50 @@ +// Source : https://leetcode.com/problems/arranging-coins/ +// Id : 441 +// Author : Fanlu Hai +// Date : 2018-04-17 +public class ArrangingCoins { + + public int arrangeCoinsWithLong(int n) { + int rows = 0; + long coins = 0; + while (true) { +// System.out.println(n + "**" + coins + " " + rows); + if (n > coins) { + rows++; + coins += rows; + } else if (n == coins) { + return rows; + } else { + return rows - 1; + } + } + } + + //faster than 82.04%, smaller than 100% + public int arrangeCoins(int n) { + int rows = 0; + long coins = 0; + while (true) { +// System.out.println(n + "**" + coins + " " + rows); + if (n > 0) { + rows++; + // use n - row instead of coins + to avoid int overflow + n -= rows; + } else if (n == 0) { + return rows; + } else { + return rows - 1; + } + } + } + + public static void main(String[] args) { + ArrangingCoins arrangingCoins = new ArrangingCoins(); + System.out.println(arrangingCoins.arrangeCoins(0)); + System.out.println(arrangingCoins.arrangeCoins(1)); + System.out.println(arrangingCoins.arrangeCoins(5)); + System.out.println(arrangingCoins.arrangeCoins(6)); + System.out.println(arrangingCoins.arrangeCoins(8)); + System.out.println(arrangingCoins.arrangeCoins(2147483647)); + } +} diff --git a/Week_01/id_26/Leetcode_50_26.java b/Week_01/id_26/Leetcode_50_26.java new file mode 100644 index 00000000..a57aff12 --- /dev/null +++ b/Week_01/id_26/Leetcode_50_26.java @@ -0,0 +1,106 @@ +// Source : https://leetcode.com/problems/powx-n/ +// Id : 50 +// Author : Fanlu Hai +// Date : 2018-04-17 +public class PowXN { + + //Time Limit Exceeded, this should be O(n) which means I need O(log(n)) or better. + public double myPowVerySlow(double x, int n) { + + double result = x; + if (n == 0) { + return 1; + } + if (n > 0) { + for (int i = 1; i < n; i++) { + result *= x; + } + return result; + } + n = -n; + for (int i = 1; i < n; i++) { + result *= x; + } + return 1 / result; + } + + // x pow of n usually means you need to multiple x for n times, we can use dichotomy to reduce it. + public double myPowWithOverflowProblem(double x, int n) { + + if (n == 0) { + return 1; + } + if (n < 0) { + //! here is the problem, -2147483648 will cause int overflow as it can't be bigger than 2147483647 + n = -n; + x = 1 / x; + } + + double result = 1; + double tmp = x; + + while (true) { + if (n == 1) { + return result * tmp; + } + if (n % 2 == 1) { + result *= tmp; + + } + n /= 2; + tmp *= tmp; + } + } + + + // x pow of n usually means you need to multiple x for n times, we can use dichotomy to reduce it. + // solved int overflow problem + // did not use recursion + // 82.1 100% + public double myPow(double x, int n) { + + boolean minValue = false; + if (n == 0 || x == 1) { + return 1; + } + + // handle -2147483648 in a not very clean way + if (n == Integer.MIN_VALUE) { + n++; + minValue = true; + } + + if (n < 0) { + n = -n; + x = 1 / x; + } + + double result = 1; + double tmp = x; + + while (true) { + if (n == 1) { + if (minValue) + return result * tmp * x; + return result * tmp; + } + if (n % 2 == 1) { + result *= tmp; + } + n /= 2; + tmp *= tmp; + } + } + + + public static void main(String[] args) { + PowXN powXN = new PowXN(); + System.out.println(powXN.myPow(2, 11)); + System.out.println(powXN.myPow(2, 12)); + System.out.println(powXN.myPow(5, -2)); + System.out.println(powXN.myPow(8, 4)); + System.out.println(powXN.myPow(0.9, 2147483647)); + System.out.println(powXN.myPow(1, -2147483647)); + System.out.println(powXN.myPow(0.3, -2147483648)); + } +} diff --git a/Week_01/id_26/Leetcode_905_26.java b/Week_01/id_26/Leetcode_905_26.java new file mode 100644 index 00000000..5f486676 --- /dev/null +++ b/Week_01/id_26/Leetcode_905_26.java @@ -0,0 +1,44 @@ +// Source : https://leetcode.com/problems/sort-array-by-parity/ +// Id : 905 +// Author : Fanlu Hai +// Date : 2018-04-15 + +import java.util.Arrays; + +class SortArrayByParity { + public int[] sortArrayByParity(int[] A) { + int i = 0; + int j = A.length - 1; + while (j > i) { +// System.out.println(Arrays.toString(A)); + if (A[i] % 2 == 1 && A[j] % 2 == 0) { + swapNumInArray(i, j, A); + } + + if (A[i] % 2 == 0) { + i++; + //in order to make sure a check is performed + continue; + } + + if (A[j] % 2 == 1) { + j--; + //in order to make sure a check is performed + continue; + } + } + return A; + } + + public void swapNumInArray(int firstIndex, int secondIndex, int[] array) { + int tmp = array[firstIndex]; + array[firstIndex] = array[secondIndex]; + array[secondIndex] = tmp; + } + + public static void main(String[] args) { + SortArrayByParity sortArrayByParity = new SortArrayByParity(); + int[] a = {1, 1, 1, 1, 2, 2, 2, 3, 3, 33, 4, 4, 5, 5, 5, 5, 6, 6, 7, 7, 7, 8}; + System.out.println(Arrays.toString(sortArrayByParity.sortArrayByParity(a))); + } +} diff --git a/Week_01/id_26/Leetcode_922_26.java b/Week_01/id_26/Leetcode_922_26.java new file mode 100644 index 00000000..b2809944 --- /dev/null +++ b/Week_01/id_26/Leetcode_922_26.java @@ -0,0 +1,50 @@ +// Source : https://leetcode.com/problems/sort-array-by-parity-ii/ +// Id : 922 +// Author : Fanlu Hai +// Date : 2018-04-15 + +import java.util.Arrays; + +class SortArrayByParityII { + public int[] sortArrayByParityII(int[] A) { + int i = 0; + int j = 1; + while (true) { +// System.out.println(A.length + " " + i + " " + j + " " + Arrays.toString(A)); + + if (i >= A.length || j >= A.length) { + return A; + } + + if (A[i] % 2 == 1 && A[j] % 2 == 0) { + swapNumInArray(i, j, A); + } + + if (A[i] % 2 == 0) { + i += 2; + //in order to make sure a check is performed + continue; + } + + if (A[j] % 2 == 1) { + j += 2; + //in order to make sure a check is performed + continue; + } + + } + + } + + public void swapNumInArray(int firstIndex, int secondIndex, int[] array) { + int tmp = array[firstIndex]; + array[firstIndex] = array[secondIndex]; + array[secondIndex] = tmp; + } + + public static void main(String[] args) { + SortArrayByParityII sortArrayByParityII = new SortArrayByParityII(); + int[] a = {1, 1, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 2, 2}; + System.out.println(Arrays.toString(sortArrayByParityII.sortArrayByParityII(a))); + } +} diff --git a/Week_01/id_26/TreeNode.java b/Week_01/id_26/TreeNode.java new file mode 100644 index 00000000..6320cd3b --- /dev/null +++ b/Week_01/id_26/TreeNode.java @@ -0,0 +1,11 @@ +package com.fanlu.leetcode.binarytree; + +public class TreeNode { + int val; + TreeNode left; + TreeNode right; + + TreeNode(int x) { + val = x; + } +} diff --git a/Week_01/id_27/LeetCode_242_027.java b/Week_01/id_27/LeetCode_242_027.java new file mode 100644 index 00000000..64a6d840 --- /dev/null +++ b/Week_01/id_27/LeetCode_242_027.java @@ -0,0 +1,17 @@ +class Solution { + public boolean isAnagram(String s, String t) { + + if(null == s || null == t) return false; + char[] sArr = s.toCharArray(); + char[] tArr = t.toCharArray(); + if(sArr.length != tArr.length) return false; + Arrays.sort(sArr); + Arrays.sort(tArr); + for(int i=0;i= arrLen) break; + nums[pos++] = tmp[i]; + if (pos>= arrLen) break; + nums[pos++] = tmp[j]; + } + + + } +} diff --git a/Week_01/id_28/LeetCode_242_028.java b/Week_01/id_28/LeetCode_242_028.java new file mode 100644 index 00000000..696ab155 --- /dev/null +++ b/Week_01/id_28/LeetCode_242_028.java @@ -0,0 +1,22 @@ +class Solution { + public boolean isAnagram(String s, String t) { + if (s.length() != t.length()) { + return false; + } + int[] stat = new int[26]; + char[] arr = s.toCharArray(); + for (char item : arr) { + stat[item - 'a']++; + } + char[] brr = t.toCharArray(); + for (char item : brr) { + stat[item - 'a']--; + } + for (int c : stat) { + if (c != 0) { + return false; + } + } + return true; + } +} diff --git a/Week_01/id_28/LeetCode_922_028.java b/Week_01/id_28/LeetCode_922_028.java new file mode 100644 index 00000000..51d98a76 --- /dev/null +++ b/Week_01/id_28/LeetCode_922_028.java @@ -0,0 +1,29 @@ +class Solution { + public int[] sortArrayByParityII(int[] A) { + int i = 0, j = A.length - 1; + while (i < A.length && j > 0) { + int a = A[i], b = A[j]; + + if (a % 2 == 1) { + if (b % 2 == 0) { // W-W + // swap + A[i] = b; + A[j] = a; + // walk both + i += 2; + j -= 2; + } else { // W-R + j -= 2; + } + } else { + if (b % 2 == 0) { // R-W + i += 2; + } else { // R-R + i += 2; + j -= 2; + } + } + } + return A; + } +} diff --git a/Week_01/id_3/LeetCode_142_3.c b/Week_01/id_3/LeetCode_142_3.c new file mode 100644 index 00000000..c626514a --- /dev/null +++ b/Week_01/id_3/LeetCode_142_3.c @@ -0,0 +1,28 @@ +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * struct ListNode *next; + * }; + */ +struct ListNode *detectCycle(struct ListNode *head) { + if (head == NULL || head->next == NULL) return NULL; + struct ListNode *fast = head, *slow = head; + + // 1st loop, check the existence of cycle + while (fast != NULL && fast->next != NULL) { + fast = fast->next->next; + slow = slow->next; + if (fast == slow) break; + } + + if (fast == NULL || fast->next == NULL) return NULL; + + // 2st loop, check the place of node which tail node connects to + struct ListNode *curr = head; + while (curr != slow) { + curr = curr->next; + slow = slow->next; + } + return curr; +} \ No newline at end of file diff --git a/Week_01/id_3/LeetCode_21_3.c b/Week_01/id_3/LeetCode_21_3.c new file mode 100644 index 00000000..62a590a4 --- /dev/null +++ b/Week_01/id_3/LeetCode_21_3.c @@ -0,0 +1,110 @@ +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * struct ListNode *next; + * }; + */ +#include +#include + +struct ListNode +{ + int val; + struct ListNode *next; +}; + +struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2) { + struct ListNode *head = NULL; + struct ListNode *tail = NULL; + struct ListNode *p = l1; + struct ListNode *q = l2; + struct ListNode *tmp; + + while(NULL != p && NULL != q) + { + //find + if(p->val <= q->val) + { + tmp = p; + p = p->next; + } + else + { + tmp = q; + q = q->next; + } + + //insert + if(NULL == head) + { + head = tmp; + tail = tmp; + } + else + { + tail->next = tmp; + tail = tmp; + } + } + + //remain + tmp = NULL != p ? p : q; + if(NULL == head) + { + head = tmp; + } + else + { + tail->next = tmp; + } + + return head; +} + +void printLinkList(struct ListNode* head) +{ + struct ListNode *p = head; + + while(NULL != p) + { + printf("%d ", p->val); + p = p->next; + } + + printf("\n"); +} + +int main() +{ + struct ListNode *l1 = NULL; + struct ListNode *l2 = NULL; + struct ListNode *l3 = NULL; + struct ListNode *p; + int a[1] = {0}; + int loop; + + for(loop = 0; loop < 0; loop++) + { + p = (struct ListNode*)malloc(sizeof(struct ListNode)); + p->val = a[loop]; + p->next = NULL == l1 ? NULL : l1; + l1 = p; + } + + for(loop = 0; loop < 1; loop++) + { + p = (struct ListNode*)malloc(sizeof(struct ListNode)); + p->val = a[loop]; + p->next = NULL == l2 ? NULL : l2; + l2 = p; + } + + printLinkList(l1); + printLinkList(l2); + + l3 = mergeTwoLists(l1, l2); + printLinkList(l3); + + return 0; +} \ No newline at end of file diff --git a/Week_01/id_3/LeetCode_24_3.c b/Week_01/id_3/LeetCode_24_3.c new file mode 100644 index 00000000..0b12498a --- /dev/null +++ b/Week_01/id_3/LeetCode_24_3.c @@ -0,0 +1,53 @@ +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * struct ListNode *next; + * }; + */ + +struct ListNode { + int val; + struct ListNode *next; +}; + +struct ListNode* swapPairs(struct ListNode* head){ + struct ListNode* prev; + struct ListNode* p; + struct ListNode *pnext; + +//特殊处理 + if(!head){ + return head; + } + + p = head; + pnext = p->next; + if(!pnext){ + return head; + } + + p->next = pnext->next; + pnext->next = p; + head = pnext; + + prev = p; + p = p->next; + + while(p){ + pnext = p->next; + if(!pnext){ + return head; + } + + prev->next = pnext; + p->next = pnext->next; + pnext->next = p; + + prev = p; + p = p->next; + } + + return head; +} + diff --git a/Week_01/id_3/LeetCode_83_3.c b/Week_01/id_3/LeetCode_83_3.c new file mode 100644 index 00000000..1465c03e --- /dev/null +++ b/Week_01/id_3/LeetCode_83_3.c @@ -0,0 +1,69 @@ +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * struct ListNode *next; + * }; + */ +#include +#include + +struct ListNode{ + int val; + struct ListNode *next; +}; + +struct ListNode* deleteDuplicates(struct ListNode* head) { + struct ListNode* p = head; + struct ListNode* q; + struct ListNode* tmp; + + while(NULL != p){ + q = p->next; + while(NULL != q && p->val == q->val){ + tmp = q; + q = q->next; + free(tmp); + } + + p->next = q; + p = p->next; + } + + return head; +} + +void printLinkList(struct ListNode* head) +{ + struct ListNode *p = head; + + while(NULL != p) + { + printf("%d ", p->val); + p = p->next; + } + + printf("\n"); +} + +int main(int argc, char *argv[]) +{ + struct ListNode *head = NULL; + struct ListNode *p; + int loop; + + for(loop = 1; loop < argc; loop++) + { + p = (struct ListNode*)malloc(sizeof(struct ListNode)); + p->val = strtol(argv[loop], 0, 10); + p->next = NULL == head ? NULL : head; + head = p; + } + + printLinkList(head); + + head = deleteDuplicates(head); + printLinkList(head); + + return 0; +} diff --git a/Week_01/id_3/LeetCode_905_3.c b/Week_01/id_3/LeetCode_905_3.c new file mode 100644 index 00000000..f6c8b167 --- /dev/null +++ b/Week_01/id_3/LeetCode_905_3.c @@ -0,0 +1,31 @@ +/** + * Note: The returned array must be malloced, assume caller calls free(). + */ + +int* sortArrayByParity(int* A, int ASize, int* returnSize){ + int* B = NULL; + int loop; + int evenIndex = 0; + int oddIndex = ASize - 1; + + if(!A){ + return NULL; + } + + B = malloc(ASize * sizeof(int)); + + for(loop = 0; loop < ASize; loop++){ + if(A[loop]%2){ + B[oddIndex] = A[loop]; + oddIndex--; + } + else{ + B[evenIndex] = A[loop]; + evenIndex++; + } + + } + + *returnSize = ASize; + return B; +} \ No newline at end of file diff --git a/Week_01/id_3/LeetCode_922_3.c b/Week_01/id_3/LeetCode_922_3.c new file mode 100644 index 00000000..cb9d80bd --- /dev/null +++ b/Week_01/id_3/LeetCode_922_3.c @@ -0,0 +1,31 @@ +/** + * Note: The returned array must be malloced, assume caller calls free(). + */ + +int* sortArrayByParityII(int* A, int ASize, int* returnSize){ + int* B = NULL; + int loop; + int evenIndex = 0; + int oddIndex = 1; + + if(!A){ + return NULL; + } + + B = malloc(ASize * sizeof(int)); + + for(loop = 0; loop < ASize; loop++){ + if(A[loop]%2){ + B[oddIndex] = A[loop]; + oddIndex+=2; + } + else{ + B[evenIndex] = A[loop]; + evenIndex+=2; + } + + } + + *returnSize = ASize; + return B; +} \ No newline at end of file diff --git a/Week_01/id_3/NOTE.md b/Week_01/id_3/NOTE.md index c684e62f..e0dd0763 100644 --- a/Week_01/id_3/NOTE.md +++ b/Week_01/id_3/NOTE.md @@ -1 +1,6 @@ -# 学习笔记 \ No newline at end of file +# 学习笔记 +本周投身项目,时间不是很充足,只做了两道简单的算法题,周日如果没事,会补做第一周的其他作业 +做了两道题:83(合并有序链表)和21(删除有序链表中的重复元素) +心得: +- ListNode *p 只是指针,如果引用未初始化的p, 比如p->next 就会发生访问访问野指针,编译器报segment fault +- 构造测试数据可以通过命令行传参: int main(int argc, char *argv[]) \ No newline at end of file diff --git a/Week_01/id_30/LeetCode_20_30.java b/Week_01/id_30/LeetCode_20_30.java new file mode 100644 index 00000000..43e7ee93 --- /dev/null +++ b/Week_01/id_30/LeetCode_20_30.java @@ -0,0 +1,51 @@ +package com.shufeng.algorithm.d0_; + +/** + * @author gsf + */ +public class LeetCode_22_30 { + + public static void main(String[] args) { + String str = "(]"; + System.out.println(isValid(str)); + + } + + public static boolean isValid(String s) { + + Stack stack = new Stack<>(); + for (int i = 0; i < s.length(); i++) { + char c = s.charAt(i); + if (c == '(' || c == '[' || c == '{') { + stack.add(s.charAt(i)); + } else { + if (stack.isEmpty()) { + return false; + } + Character pop = stack.pop(); + if (c == ')' && pop != '(') { + return false; + } + if (c == ']' && pop != '[') { + return false; + } + if (c == '}' && pop != '{') { + return false; + } + + } + } + return stack.isEmpty(); + } + // 虽然慢,面试让我说就说栈,让我写,写这个嘿嘿。 + public boolean isValid1(String s) { + while (s.length() != 0) { + int length = s.length(); + s = s.replace("()", "").replace("[]", "").replace("{}", ""); + if (length == s.length()) { + return false; + } + } + return true; + } +} diff --git a/Week_01/id_30/LeetCode_21_30.java b/Week_01/id_30/LeetCode_21_30.java new file mode 100644 index 00000000..b3e787d6 --- /dev/null +++ b/Week_01/id_30/LeetCode_21_30.java @@ -0,0 +1,26 @@ +package com.shufeng.algorithm.d0_; + +import com.shufeng.algorithm.dto.ListNode; + +/** + * @author gsf + */ +public class LeetCode_21_30 { + + public static ListNode mergeTwoLists(ListNode l1, ListNode l2) { + ListNode node = new ListNode(0); + ListNode first = node; + while (l1 != null && l2 != null) { + if (l1.val > l2.val) { + node.next = l2; + l2 = l2.next; + } else { + node.next = l1; + l1 = l1.next; + } + node = node.next; + } + node.next = l1 != null ? l1 : l2; + return first.next; + } +} diff --git a/Week_01/id_30/LeetCode_242_30.java b/Week_01/id_30/LeetCode_242_30.java new file mode 100644 index 00000000..c35e2dc8 --- /dev/null +++ b/Week_01/id_30/LeetCode_242_30.java @@ -0,0 +1,21 @@ +package com.shufeng.algorithm.d0_; + +/** + * @author gsf + */ +public class LeetCode_242_30 { + + public static void main(String[] args) { + + String s = "anagram", t = "nagaram"; + System.out.println(isAnagram(s, t)); + } + + public static boolean isAnagram(String s, String t) { + char[] ss = s.toCharArray(); + char[] tt = t.toCharArray(); + Arrays.sort(ss); + Arrays.sort(tt); + return String.valueOf(ss).equals(String.valueOf(tt)); + } +} diff --git a/Week_01/id_30/LeetCode_441_30.java b/Week_01/id_30/LeetCode_441_30.java new file mode 100644 index 00000000..0599ceb6 --- /dev/null +++ b/Week_01/id_30/LeetCode_441_30.java @@ -0,0 +1,31 @@ +package com.shufeng.algorithm.d0_; + +/** + * @author gsf + */ +public class LeetCode_441_30 { + + public static void main(String[] args) { + int i = arrangeCoins(5); + System.out.println(i); + } + public static int arrangeCoins(int n) { + if (n <= 1) { + return n; + } + long low = 0; + long high = n; + while (low < high) { + // 二分法查询硬币可以摆放的行数 + long mid = low + (high - low) / 2; + // 核心公式 放满n行用的硬币数:n*(n+1)/2 + // 如果给的硬币数大于mid,证明比这行多去右面去找行数,如果小去左边找行数 + if (mid * (mid + 1) / 2 <= n) { + low = mid + 1; + } else { + high = mid; + } + } + return (int) (low - 1); + } +} diff --git a/Week_01/id_30/LeetCode_687_30.java b/Week_01/id_30/LeetCode_687_30.java new file mode 100644 index 00000000..338a633e --- /dev/null +++ b/Week_01/id_30/LeetCode_687_30.java @@ -0,0 +1,33 @@ +package com.shufeng.algorithm.d0_; + +/** + * @author gsf + */ +public class LeetCode_687_30 { + + public static void main(String[] args) { + TreeNode bst = new TreeNode(1); + bst.left = new TreeNode(4); + bst.right = new TreeNode(5); + bst.left.left = new TreeNode(4); + bst.left.right = new TreeNode(4); + bst.right.left = new TreeNode(5); + + int i = longestUnivaluePath(bst); + System.out.println(i); + } + public static int longestUnivaluePath(TreeNode root) { + if (root == null) { + return 0; + } + int max = Math.max(longestUnivaluePath(root.left), longestUnivaluePath(root.right)); + return Math.max(max, recursion(root.left, root.val) + recursion(root.right, root.val)); + } + public static int recursion(TreeNode node, int pVal) { + if (node == null || node.val != pVal) { + return 0; + } + return Math.max(recursion(node.left, node.val), recursion(node.right, node.val)) + 1; + } + +} diff --git a/Week_01/id_30/LeetCode_83_30.java b/Week_01/id_30/LeetCode_83_30.java new file mode 100644 index 00000000..89a39cce --- /dev/null +++ b/Week_01/id_30/LeetCode_83_30.java @@ -0,0 +1,21 @@ +package com.shufeng.algorithm.d0_; + +import com.shufeng.algorithm.dto.ListNode; + +/** + * @author gsf + */ +public class LeetCode_83_30 { + public static ListNode deleteDuplicates(ListNode head) { + ListNode head1 = head; + while (head1 != null) { + if (head1.next != null && head1.val == head1.next.val) { + head1.next = head1.next.next; + continue; + } + head1 = head1.next; + } + return head; + + } +} diff --git a/Week_01/id_30/LeetCode_905_30.java b/Week_01/id_30/LeetCode_905_30.java new file mode 100644 index 00000000..b7d7c984 --- /dev/null +++ b/Week_01/id_30/LeetCode_905_30.java @@ -0,0 +1,29 @@ +package com.shufeng.algorithm.d0_; + +/** + * @author gsf + */ +public class LeetCode_905_30 { + + public static int[] sortArrayByParity(int[] A) { + if (A == null || A.length == 0 || A.length == 1) { + return A; + } + int j = A.length - 1; + int i = 0; + while (i < j) { + if ((A[i] & 1) == 1) { + swap(A, i, j); + j--; + continue; + } + i++; + } + return A; + } + public static void swap(int[] arr, int i, int j) { + int tem = arr[i]; + arr[i] = arr[j]; + arr[j] = tem; + } +} diff --git a/Week_01/id_30/LeetCode_922_30.java b/Week_01/id_30/LeetCode_922_30.java new file mode 100644 index 00000000..8022bc19 --- /dev/null +++ b/Week_01/id_30/LeetCode_922_30.java @@ -0,0 +1,39 @@ +package com.shufeng.algorithm.d0_; + +/** + * @author gsf + */ +public class LeetCode_922_30 { + + public static void main(String[] args) { + int[] arr = {2, 3, 1, 1, 4, 0, 0, 4, 3, 3}; + int[] ints = sortArrayByParity(arr); + System.out.println(Arrays.toString(ints)); + } + + public static int[] sortArrayByParity(int[] A) { + if (A == null || A.length == 0 || A.length == 1) { + return A; + } + int j = 0; + int i = 1; + while (j < A.length && i < A.length) { + if ((A[i] & 1) == (i & 1)) { + i += 2; + continue; + } + if ((A[j] & 1) == (j & 1)) { + j += 2; + continue; + } + swap(A, i, j); + } + return A; + } + + public static void swap(int[] arr, int i, int j) { + int tem = arr[i]; + arr[i] = arr[j]; + arr[j] = tem; + } +} diff --git a/Week_01/id_30/NOTE.md b/Week_01/id_30/NOTE.md index c684e62f..78cede1a 100644 --- a/Week_01/id_30/NOTE.md +++ b/Week_01/id_30/NOTE.md @@ -1 +1,10 @@ -# 学习笔记 \ No newline at end of file +# 学习笔记 +第一周做题学习总结 + +- 链表 + - 链表注意应用变量的使用 +- 递归 + - 了解到递归,从上到下和从下到上简单使用和逻辑 + - 687 了解到了递归的多种递归组合使用。 +- 二分查找 + - 441 二分查找的新用法。 \ No newline at end of file diff --git a/Week_01/id_31/LeetCode_153_031.swift b/Week_01/id_31/LeetCode_153_031.swift new file mode 100644 index 00000000..dc42dada --- /dev/null +++ b/Week_01/id_31/LeetCode_153_031.swift @@ -0,0 +1,21 @@ +// +// LeetCode_153_031.swift +// TestCoding +// +// Created by 龚欢 on 2019/4/15. +// Copyright © 2019 龚欢. All rights reserved. +// + +import Foundation + +// 时间复杂度 O(n) +class Solution { + func findMin(_ nums: [Int]) -> Int { + guard nums.count > 0 else { return -1 } + if var result = nums.first { + _ = nums.map { result = min(result, $0) } + return result + } + return -1 + } +} diff --git a/Week_01/id_31/LeetCode_164_031.swift b/Week_01/id_31/LeetCode_164_031.swift new file mode 100644 index 00000000..8d37ae28 --- /dev/null +++ b/Week_01/id_31/LeetCode_164_031.swift @@ -0,0 +1,50 @@ +// +// LeetCode_164_031.swift +// TestCoding +// +// Created by 龚欢 on 2019/4/19. +// Copyright © 2019 龚欢. All rights reserved. +// + +import Foundation + +class Solution { + func maximumGap(_ nums: [Int]) -> Int { + guard nums.count > 0 else { return 0 } + var nums = nums + qSort(&nums, 0, nums.count - 1) + var maxSpace = 0 + for i in 0...nums.count - 1 { + if (nums.count > i + 1) { + maxSpace = max(maxSpace, nums[i+1] - nums[i]) + } + } + return maxSpace + } + + private func qSort(_ nums: inout [Int], _ from: Int, _ to:Int) { + if from < to { + let mid = findPartition(&nums, from, to) + qSort(&nums, from, mid) + qSort(&nums, mid + 1, to) + } + } + + private func findPartition(_ nums: inout [Int], _ from: Int, _ to: Int) -> Int { + var from = from + var to = to + let indexNumber = nums[from] + while from < to { + while nums[to] >= indexNumber && from < to { + to -= 1 + } + nums[from] = nums[to] + while nums[from] <= indexNumber && from < to { + from += 1 + } + nums[to] = nums[from] + } + nums[from] = indexNumber + return from + } +} diff --git a/Week_01/id_31/LeetCode_20_031.swift b/Week_01/id_31/LeetCode_20_031.swift new file mode 100644 index 00000000..38064abd --- /dev/null +++ b/Week_01/id_31/LeetCode_20_031.swift @@ -0,0 +1,23 @@ +// +// LeetCode_20_031.swift +// TestCoding +// +// Created by 龚欢 on 2019/4/16. +// Copyright © 2019 龚欢. All rights reserved. +// + +import Foundation + +class Solution { + var stack: [Character] = [] + func isValid(_ s: String) -> Bool { + _ = s.map { + if let lastChar = stack.last, ((lastChar == "{" && $0 == "}") || (lastChar == "(" && $0 == ")") || (lastChar == "[" && $0 == "]")) { + stack.removeLast() + } else { + stack.append($0) + } + } + return stack.isEmpty + } +} diff --git a/Week_01/id_31/LeetCode_242_031.swift b/Week_01/id_31/LeetCode_242_031.swift new file mode 100644 index 00000000..1f237787 --- /dev/null +++ b/Week_01/id_31/LeetCode_242_031.swift @@ -0,0 +1,36 @@ +// +// LeetCode_242_031.swift +// TestCoding +// +// Created by 龚欢 on 2019/4/18. +// Copyright © 2019 龚欢. All rights reserved. +// + +import Foundation + +class Solution { + func isAnagram(_ s: String, _ t: String) -> Bool { + if (s.count != t.count) { return false } + var collect: [Character: Int] = [:] + for sChar in s { + if collect.keys.contains(sChar), var sValue = collect[sChar] { + sValue += 1 + collect[sChar] = sValue + } else { + collect[sChar] = 1 + } + } + + for tChar in t { + if collect.keys.contains(tChar), var tValue = collect[tChar], tValue > 0 { + tValue -= 1 + if (tValue == 0) { + collect.removeValue(forKey: tChar) + } else { + collect[tChar] = tValue + } + } + } + return collect.isEmpty + } +} diff --git a/Week_01/id_31/LeetCode_324_031.swift b/Week_01/id_31/LeetCode_324_031.swift new file mode 100644 index 00000000..4183d118 --- /dev/null +++ b/Week_01/id_31/LeetCode_324_031.swift @@ -0,0 +1,81 @@ +// +// LeetCode_324_031.swift +// TestCoding +// +// Created by 龚欢 on 2019/4/19. +// Copyright © 2019 龚欢. All rights reserved. +// + +import Foundation + +class Solution { + func wiggleSort(_ nums: inout [Int]) { + qSort(0, nums.count - 1, &nums) + createWiggle(&nums) + } + + private func createWiggle(_ nums: inout [Int], _ fromLeft: Bool = true) { + var data: [Int] = [] + var from = 0 + var to = nums.count - 1 + var mid = (from + to) / 2 + if fromLeft { + for _ in from...mid { + if (from < nums.count) { + if data.count > 0, let last = data.last, nums[from] >= last { + return createWiggle(&nums, false) + } + data.append(nums[from]) + from += 1 + } + if (mid + 1 < nums.count) { + if data.count > 0, let last = data.last, nums[mid+1] <= last { + return createWiggle(&nums, false) + } + data.append(nums[mid + 1]) + mid += 1 + } + } + } else { + let mIndex = mid + for _ in mid...to { + if (mid >= 0) { + data.append(nums[mid]) + mid -= 1 + } + if (to > mIndex) { + data.append(nums[to]) + to -= 1 + } + } + } + nums = data + } + + private func qSort(_ from: Int, _ to: Int, _ nums: inout [Int]) { + if from < to { + let mid = findPartition(from, to, &nums) + qSort(from, mid - 1, &nums) + qSort(mid + 1, to, &nums) + } + } + + private func findPartition(_ from: Int, _ to: Int, _ nums: inout [Int]) -> Int { + let indexNumber = nums[from] + var from = from + var to = to + while from < to { + while nums[to] >= indexNumber && from < to { + to -= 1 + } + nums[from] = nums[to] + + while nums[from] <= indexNumber && from < to { + from += 1 + } + nums[to] = nums[from] + } + nums[from] = indexNumber + return from + } +} diff --git a/Week_01/id_31/LeetCode_33_031.swift b/Week_01/id_31/LeetCode_33_031.swift new file mode 100644 index 00000000..ca9b0140 --- /dev/null +++ b/Week_01/id_31/LeetCode_33_031.swift @@ -0,0 +1,65 @@ +// +// LeetCode_33_031.swift +// TestCoding +// +// Created by 龚欢 on 2019/4/18. +// Copyright © 2019 龚欢. All rights reserved. +// + +import Foundation + +class Solution { + var temp: [Int: Int] = [:] + func search(_ nums: [Int], _ target: Int) -> Int { + var nums = nums + if (nums.isEmpty) { return -1 } + for i in 0...nums.count - 1 { temp[nums[i]] = i } + qSort(0, nums.count - 1, &nums) + return binaryFind(nums, target, 0, nums.count - 1) + } + + private func binaryFind(_ nums: [Int], _ target: Int, _ from: Int, _ to: Int) -> Int { + if (from > to) { return -1 } + var from = from + var to = to + let mid = (from + to) / 2 + if nums[mid] == target { + if let v = temp[nums[mid]] { return v } + return -1 + } else if nums[mid] > target { + to = mid - 1 + return binaryFind(nums, target, from, to) + } else { + from = mid + 1 + return binaryFind(nums, target, from, to) + } + } + + private func qSort(_ from: Int, _ to: Int, _ nums: inout [Int]) { + if from < to { + let findPartition = partition(from, to, &nums) + qSort(from, findPartition - 1, &nums) + qSort(findPartition + 1, to, &nums) + } + } + + + private func partition(_ from: Int, _ to: Int, _ nums: inout [Int]) -> Int { + let indexNumber = nums[from] + var i = from + var j = to + while i < j { + while nums[j] >= indexNumber && i < j { + j -= 1 + } + nums[i] = nums[j] + + while nums[i] <= indexNumber && i < j { + i += 1 + } + nums[j] = nums[i] + } + nums[i] = indexNumber + return i + } +} diff --git a/Week_01/id_31/LeetCode_441_031.swift b/Week_01/id_31/LeetCode_441_031.swift new file mode 100644 index 00000000..139630d3 --- /dev/null +++ b/Week_01/id_31/LeetCode_441_031.swift @@ -0,0 +1,27 @@ +// +// LeetCode_441_031.swift +// TestCoding +// +// Created by 龚欢 on 2019/4/19. +// Copyright © 2019 龚欢. All rights reserved. +// + +import Foundation + +class Solution { + func arrangeCoins(_ n: Int) -> Int { + var total = 0 + var k = 1 + let n = n + while n >= k { + total += k + if total == n { + return k + } else if total > n { + return k - 1 + } + k += 1 + } + return 0 + } +} diff --git a/Week_01/id_31/LeetCode_50_031.swift b/Week_01/id_31/LeetCode_50_031.swift new file mode 100644 index 00000000..c587fecd --- /dev/null +++ b/Week_01/id_31/LeetCode_50_031.swift @@ -0,0 +1,22 @@ +// +// LeetCode_50_031.swift +// TestCoding +// +// Created by 龚欢 on 2019/4/20. +// Copyright © 2019 龚欢. All rights reserved. +// + +import Foundation + +class Solution { + func myPow(_ x: Double, _ n: Int) -> Double { + if n == 0 { return 1 } + if n == 1 { return x } + let tempValue = myPow(x, n/2) + if (n % 2 == 0) { + return tempValue * tempValue + } else { + return pow(x, Double(n + 1)) / x + } + } +} diff --git a/Week_01/id_31/LeetCode_687_031.swift b/Week_01/id_31/LeetCode_687_031.swift new file mode 100644 index 00000000..b93b6d71 --- /dev/null +++ b/Week_01/id_31/LeetCode_687_031.swift @@ -0,0 +1,36 @@ +// +// LeetCode_687_031.swift +// TestCoding +// +// Created by 龚欢 on 2019/4/19. +// Copyright © 2019 龚欢. All rights reserved. +// + +import Foundation + +class Solution { + func longestUnivaluePath(_ root: TreeNode?) -> Int { + guard let _ = root else { return 0 } + let childrenPath = max(longestUnivaluePath(root?.left), longestUnivaluePath(root?.right)) + let s = search(root) + let rootPath = s.left + s.right + return max(childrenPath, rootPath) + } + + private func search(_ root: TreeNode?) -> (left: Int, right: Int) { + guard let rootv = root else { return (left: 0, right: 0) } + var leftv: Int = 0 + var rightv: Int = 0 + if rootv.left?.val == rootv.val { + leftv = 1 + findMax(search(root?.left)) + } + if rootv.right?.val == rootv.val { + rightv = 1 + findMax(search(root?.right)) + } + return (left: leftv, right: rightv) + } + + private func findMax(_ t: (Int, Int)) -> Int { + return max(t.0, t.1) + } +} diff --git a/Week_01/id_31/LeetCode_81_031.swift b/Week_01/id_31/LeetCode_81_031.swift new file mode 100644 index 00000000..600b99c0 --- /dev/null +++ b/Week_01/id_31/LeetCode_81_031.swift @@ -0,0 +1,15 @@ +// +// LeetCode_81_031.swift +// TestCoding +// +// Created by 龚欢 on 2019/4/15. +// Copyright © 2019 龚欢. All rights reserved. +// + +import Foundation + +class Solution { + func search(_ nums: [Int], _ target: Int) -> Bool { + return nums.contains(target) + } +} diff --git a/Week_01/id_33/LeetCode_242_33.py b/Week_01/id_33/LeetCode_242_33.py new file mode 100644 index 00000000..0d1caae1 --- /dev/null +++ b/Week_01/id_33/LeetCode_242_33.py @@ -0,0 +1,26 @@ +class Solution(object): + def isAnagram(self, s, t): + """ + :type s: str + :type t: str + :rtype: bool + """ + A = [0] * 26 + if len(t) != len(s): + return False + for i in range(len(s)): + A[ord(s[i])-ord('a')] += 1 + for i in range(len(t)): + A[ord(t[i])-ord('a')] -= 1 + for i in range(26): + if A[i] != 0: + return False + return True + +s = "anagram" +t = "nagaram" + +solution = Solution() +print(solution.isAnagram(s, t)) + + diff --git a/Week_01/id_33/LeetCode_905_33.py b/Week_01/id_33/LeetCode_905_33.py new file mode 100644 index 00000000..947e7198 --- /dev/null +++ b/Week_01/id_33/LeetCode_905_33.py @@ -0,0 +1,19 @@ +class Solution: + def sortArrayByParity(self, A: List[int]) -> List[int]: + i = 0 + j = len(A) - 1 + while i < j: + if A[i] % 2 == 1 and A[j] % 2 == 0: + A[i], A[j] = A[j], A[i] + i += 1 + j -= 1 + while i < j and A[j] % 2 == 1: + j -= 1 + while i < j and A[i] % 2 == 0: + i += 1 + return A + +s = Solution() +a = [3, 1, 2, 4] +output = s.sortArrayByParity(a) +print(output) \ No newline at end of file diff --git a/Week_01/id_34/LeetCode_83_0.cs b/Week_01/id_34/LeetCode_83_0.cs new file mode 100644 index 00000000..fa2286c4 --- /dev/null +++ b/Week_01/id_34/LeetCode_83_0.cs @@ -0,0 +1,29 @@ + public class Solution + { + public ListNode DeleteDuplicates(ListNode head) + { + int currentValue = head.val; + int nextValue = 0; + + + if(head == null|| head.next==null) + { return head; } + + ListNode copyHead = head; + while(copyHead.next!=null) + { + currentValue = copyHead.val; + nextValue = copyHead.next.val; + if(currentValue==nextValue) + { + copyHead.next = copyHead.next.next; + } + else + { + copyHead = copyHead.next; + } + } + + return head; + } + } diff --git a/Week_01/id_34/LeetCode_905_0.cs b/Week_01/id_34/LeetCode_905_0.cs new file mode 100644 index 00000000..2ca32675 --- /dev/null +++ b/Week_01/id_34/LeetCode_905_0.cs @@ -0,0 +1,38 @@ + public class Solution + { + public int[] SortArrayByParity(int[] A) + { + if (A == null && A.Length == 0) + { + return A; + } + int indexHead = 0; + int indexTail = A.Length - 1; + int tempValue = 0; + while (indexHead < indexTail) + { + if (A[indexHead] % 2 == 1 && A[indexTail] % 2 == 0) + { + tempValue = A[indexHead]; + A[indexHead] = A[indexTail]; + A[indexTail] = tempValue; + indexHead++; + indexTail--; + } + else if (A[indexHead] % 2 == 0 && A[indexTail] % 2 == 1) + { + indexHead++; + indexTail--; + } + else if (A[indexHead] % 2 == 1) + { + indexTail--; + } + else if (A[indexTail] % 2 == 0) + { + indexHead++; + } + } + return A; + } + } diff --git a/Week_01/id_36/LeetCode_441_036_ArrangeCoins.java b/Week_01/id_36/LeetCode_441_036_ArrangeCoins.java new file mode 100644 index 00000000..e69de29b diff --git a/Week_01/id_36/LeetCode_687_036_LongestUnivaluePath.java b/Week_01/id_36/LeetCode_687_036_LongestUnivaluePath.java new file mode 100644 index 00000000..bb10085f --- /dev/null +++ b/Week_01/id_36/LeetCode_687_036_LongestUnivaluePath.java @@ -0,0 +1,90 @@ +package com.geek.week01; + +/** + * @author dehuab + * https://leetcode-cn.com/problems/longest-univalue-path/ * + * 687. 最长同值路径 + * Given a binary tree, find the length of the longest path where each node in the path has the same value. This path may or may not pass through the root. + *

+ * Note: The length of path between two nodes is represented by the number of edges between them. + *

+ * 示例 1: + *

+ * 输入: + *

+ * 5 + * / \ + * 4 5 + * / \ \ + * 1 1 5 + * 输出: + *

+ * 2 + * 示例 2: + *

+ * 输入: + *

+ * 1 + * / \ + * 4 5 + * / \ \ + * 4 4 5 + * 输出: + *

+ * 2 + * 注意: 给定的二叉树不超过10000个结点。 树的高度不超过1000。 + */ +public class LeetCode_687_036_LongestUnivaluePath { + public int longestUnivaluePath(TreeNode root) { + int[] count = new int[1]; + getLongestPathCount(root, count); + return count[0]; + } + + private int getLongestPathCount(TreeNode node, int[] longestPath) { + if (node == null) { + return 0; + } + + int leftCount = getLongestPathCount(node.left, longestPath); + int rightCount = getLongestPathCount(node.right, longestPath); + + if (node.left != null && node.left.val == node.val) { + leftCount++; + } else { + leftCount = 0; + } + + if (node.right != null && node.right.val == node.val) { + rightCount++; + } else { + rightCount = 0; + } + + int currentLongestPath; + if (node.left != null && node.right != null && node.left.val == node.right.val) { + /* 如果左右节点的值相同,那么可以相加连接起来。但如果左右相同但和本节点值不同,那么left和right的值都是0 */ + currentLongestPath = leftCount + rightCount; + } else { + /* 否则,最大的路径值只能是左右路径的最大值 */ + currentLongestPath = Math.max(leftCount, rightCount); + } + + if (currentLongestPath > longestPath[0]) { + /* 最终返回的结果在这里,每次递归都是以当前节点为核心,计算最大路径值,在多次递归当中,仅保留最大的值 */ + longestPath[0] = currentLongestPath; + } + /* 递归返回的是本节点与左右两个子节点的同值路径的最大值,注意,如果本节点的值与左右节点的值都不同,那么返回的是0 */ + return Math.max(leftCount, rightCount); + } +} + +class TreeNode { + int val; + TreeNode left; + TreeNode right; + + TreeNode(int x) { + val = x; + } +} \ No newline at end of file diff --git a/Week_01/id_37/LeetCode_153_37.java b/Week_01/id_37/LeetCode_153_37.java new file mode 100644 index 00000000..106beb03 --- /dev/null +++ b/Week_01/id_37/LeetCode_153_37.java @@ -0,0 +1,18 @@ +class Solution { + public int findMin(int[] nums) { + int low =0; + int high = nums.length-1; + + while(lownums[high]){ + low = mid+1; + }else{ + high = mid; + } + } + + return nums[low]; + } +} diff --git a/Week_01/id_37/LeetCode_905_37.java b/Week_01/id_37/LeetCode_905_37.java new file mode 100644 index 00000000..f8ea2c48 --- /dev/null +++ b/Week_01/id_37/LeetCode_905_37.java @@ -0,0 +1,21 @@ +class Solution { + public int[] sortArrayByParity(int[] A) { + int[] res=new int[A.length]; + int left=0; + int right=A.length-1; + + for(int i=0;i len(nums): + return False + total = sum(nums) + if total % k > 0: + return False + target = total / k + nums = sorted(nums) + row = len(nums) - 1 + while nums[row] == target: + row -= 1 + k -= 1 + groups = [0] * k + return self.search(groups, row, nums, target) + + def search(self, groups, row, nums, target): + if row < 0: + return True + value = nums[row] + row -= 1 + for i in range(0, len(groups)): + if groups[i] + value <= target: + groups[i] += value + if self.search(groups, row, nums, target): + return True + groups[i] -= value + if groups[i] == 0: + break + return False + + diff --git a/Week_01/id_39/LeetCode_083_039.java b/Week_01/id_39/LeetCode_083_039.java new file mode 100644 index 00000000..5ddfe8bc --- /dev/null +++ b/Week_01/id_39/LeetCode_083_039.java @@ -0,0 +1,28 @@ +package com.paula.algorithmsAndDataStructure.leetCode_83; + +public class LeetCode_083_039 { + public ListNode deleteDuplicates(ListNode head) { + if(head == null) return null; + + ListNode p = head; + ListNode q = null; + while(p.next != null) { + if(p.val == p.next.val) { + if(q == null || (q != null && q.val != p.val)) { + q = p; + } + }else { + if(q != null && q.val == p.val) { + q.next = p.next; + } + } + p = p.next; + } + + if(q != null && p.val == q.val && p.next == null) { + q.next = null; + } + return head; + } + +} diff --git a/Week_01/id_39/LeetCode_922_039.java b/Week_01/id_39/LeetCode_922_039.java new file mode 100644 index 00000000..92c79865 --- /dev/null +++ b/Week_01/id_39/LeetCode_922_039.java @@ -0,0 +1,42 @@ +package com.paula.algorithmsAndDataStructure; + +public class LeetCode_922_039 { + public int[] sortArrayByParityII(int[] A) { + int len = A.length; + int i=0; //偶数下标 + int j=i+1; //奇数下标 + Boolean evenIndexOddValue = false; + Boolean oddIndexEvenValue = false; + + while (i < len-1 && j < len) { + evenIndexOddValue = isOdd(A[i]); + oddIndexEvenValue= isEven(A[j]); + + if(!evenIndexOddValue) i +=2; + if(!oddIndexEvenValue) j +=2; + if(evenIndexOddValue && oddIndexEvenValue) { + int tempVal = A[i]; + A[i] = A[j]; + A[j] = tempVal; + + i += 2; + j += 2; + + } + } + + + return A; + } + + public boolean isEven(int value) { + + return value%2 == 0 ? true : false; + } + + public boolean isOdd(int value) { + + return value%2 == 1 ? true : false; + } + +} diff --git a/Week_01/id_40/LeetCode_83_040.go b/Week_01/id_40/LeetCode_83_040.go new file mode 100644 index 00000000..86b5b1fe --- /dev/null +++ b/Week_01/id_40/LeetCode_83_040.go @@ -0,0 +1,11 @@ +func deleteDuplicates(head *ListNode) *ListNode { + current := head + for current != nil && current.Next != nil { + if current.Next.Data == current.Data { + current.Next = current.Next.Next + } else { + current = current.Next + } + } + return head +} diff --git a/Week_01/id_40/LeetCode_905_040.go b/Week_01/id_40/LeetCode_905_040.go new file mode 100644 index 00000000..63c4726b --- /dev/null +++ b/Week_01/id_40/LeetCode_905_040.go @@ -0,0 +1,31 @@ +package main + +import "fmt" + +func sortArrayByParity(A []int) []int { + if A == nil || len(A) == 1 { + return A + } + left := 0 + right := len(A) - 1 + for left < right { + //左指针对应偶数值,右指针对应奇数值,进行交换 + if (A[left]&1) == 1 && (A[right]&1) == 0 { + A[left], A[right] = A[right], A[left] + } else if (A[left] & 1) == 0 { + //左指针对应的是偶数值,符合题意,继续向右移动 + left++ + } else if (A[right] & 1) == 1 { + //右指针对应的是奇数值,符合题意,继续向左移动 + right-- + } + } + return A +} + +func main() { + fmt.Println("vim-go") + x := []int{1, 2, 3} + x = []int{1} + fmt.Println(sortArrayByParity(x)) +} diff --git a/Week_01/id_44/LeetCode_142_044.java b/Week_01/id_44/LeetCode_142_044.java new file mode 100644 index 00000000..38151428 --- /dev/null +++ b/Week_01/id_44/LeetCode_142_044.java @@ -0,0 +1,32 @@ +public class LeetCode_142_044 { + public ListNode Solution(ListNode head) { + if (head == null || head.next == null) + return null; + ListNode fast = head; + ListNode slow = head; + + while (fast != null && fast.next != null) { + slow = slow.next; + fast = fast.next.next; + if (fast == slow) { + ListNode find = head; + while (find != slow) { + find = find.next; + slow = slow.next; + } + return find; + } + } + return null; + } +} + +class ListNode { + int val; + ListNode next; + + ListNode(int x) { + val = x; + next = null; + } +} diff --git a/Week_01/id_44/LeetCode_441_044.java b/Week_01/id_44/LeetCode_441_044.java new file mode 100644 index 00000000..6cf6c71e --- /dev/null +++ b/Week_01/id_44/LeetCode_441_044.java @@ -0,0 +1,22 @@ +public class LeetCode_441_044 { + public int solution(int n) { + int i = 1; + int sub = n; + int res = 0; + for (i = 1; i <= n; i++) { + sub = sub - i; + if (sub - (i + 1) < 0) { + res = i; + break; + } + if (sub - (i + 1) == 0) { + res = i + 1; + break; + } + if (sub - (i + 1) > 0) { + continue; + } + } + return res; + } +} diff --git a/Week_01/id_45/LeetCode_21_45.java b/Week_01/id_45/LeetCode_21_45.java new file mode 100644 index 00000000..73b58963 --- /dev/null +++ b/Week_01/id_45/LeetCode_21_45.java @@ -0,0 +1,33 @@ +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode(int x) { val = x; } + * } + */ +class Solution { + public ListNode mergeTwoLists(ListNode l1, ListNode l2) { + ListNode dummyHead = new ListNode(0); + ListNode current = dummyHead; + while(l1 != null && l2 != null){ + ListNode tempNode = new ListNode(0); + if(l1.val < l2.val){ + tempNode.val = l1.val; + l1 = l1.next; + } else { + tempNode.val = l2.val; + l2 = l2.next; + } + current.next = tempNode; + current = tempNode; + } + if(l1 == null){ + current.next = l2; + } + if(l2 == null){ + current.next = l1; + } + return dummyHead.next; + } +} diff --git a/Week_01/id_45/LeetCode_24_45.java b/Week_01/id_45/LeetCode_24_45.java new file mode 100644 index 00000000..fe935820 --- /dev/null +++ b/Week_01/id_45/LeetCode_24_45.java @@ -0,0 +1,27 @@ +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode(int x) { val = x; } + * } + */ +class Solution { + public ListNode swapPairs(ListNode head) { + if(head == null) { + return head; + } + ListNode curr = head; + while (curr.next != null) { + int temp = curr.next.val; + curr.next.val = curr.val; + curr.val = temp; + if(curr.next.next == null){ + return head; + } else { + curr = curr.next.next; + } + } + return head; + } +} diff --git a/Week_01/id_46/leetcode_142_046.cpp b/Week_01/id_46/leetcode_142_046.cpp new file mode 100644 index 00000000..1696fe29 --- /dev/null +++ b/Week_01/id_46/leetcode_142_046.cpp @@ -0,0 +1,24 @@ +/** + * 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) { + set res; + while(head){ + auto it = res.find(head); + if(it!=res.end()) + return head; + else{ + res.insert(head); + head = head->next; + } + } + return NULL; + } +}; diff --git a/Week_01/id_46/leetcode_21_046.cpp b/Week_01/id_46/leetcode_21_046.cpp new file mode 100644 index 00000000..b79b6390 --- /dev/null +++ b/Week_01/id_46/leetcode_21_046.cpp @@ -0,0 +1,39 @@ +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode(int x) : val(x), next(NULL) {} + * }; + */ +class Solution { +public: + ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { + if(!l1 && !l2) return NULL; + ListNode* head = new ListNode(0); + ListNode* pre = head; + while(l1 && l2){ + if(l1->val<=l2->val){ + head->next = l1; + head=head->next; + l1=l1->next; + } + else { + head->next = l2; + head=head->next; + l2=l2->next; + } + } + while(l1){ + head->next = l1; + head=head->next; + l1=l1->next; + } + while(l2){ + head->next = l2; + head=head->next; + l2=l2->next; + } + return pre->next; + } +}; diff --git a/Week_01/id_46/leetcode_24_046.cpp b/Week_01/id_46/leetcode_24_046.cpp new file mode 100644 index 00000000..3195a3fd --- /dev/null +++ b/Week_01/id_46/leetcode_24_046.cpp @@ -0,0 +1,27 @@ +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode(int x) : val(x), next(NULL) {} + * }; + */ +class Solution { +public: + ListNode* swapPairs(ListNode* head) { + if(!head || !head->next) return head; + ListNode* pre=new ListNode(0); + pre->next=head; + ListNode*cur=pre; + while(cur->next && cur->next->next){ + ListNode* tmp1 = cur->next; + ListNode* tmp2 = tmp1->next; + ListNode* tmp3 = tmp2->next; + tmp2->next=tmp1; + tmp1->next = tmp3; + cur->next = tmp2; + cur=tmp1; + } + return pre->next; + } +}; diff --git a/Week_01/id_46/leetcode_503_046.cpp b/Week_01/id_46/leetcode_503_046.cpp new file mode 100644 index 00000000..cb89248f --- /dev/null +++ b/Week_01/id_46/leetcode_503_046.cpp @@ -0,0 +1,19 @@ +class Solution { +public: + vector nextGreaterElements(vector& nums) { + vector res(nums.size(),-1); + stack> stk; + int len = nums.size(); + for(int i=0; i(nums[i], i)); + } + } + return res; + } +}; diff --git a/Week_01/id_46/leetcode_687_046.cpp b/Week_01/id_46/leetcode_687_046.cpp new file mode 100644 index 00000000..d22bd8e5 --- /dev/null +++ b/Week_01/id_46/leetcode_687_046.cpp @@ -0,0 +1,40 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} + * }; + */ +class Solution { +public: + int respath=0; + int longestUnivaluePath(TreeNode* root) { + if(!root) return 0; + maxpath(root); + return respath; + } + int maxpath(TreeNode* root){ + int res=0,le=0,ri=0,nextLen;; + if(!root->left && !root->right) return 0; + if(root->left){ + nextLen = maxpath(root->left); + if(root->val==(root->left)->val){ + le = nextLen+1; + res += le; + } + else le=0; + } + if(root->right){ + nextLen = maxpath(root->right); + if(root->val==(root->right)->val){ + ri = nextLen+1; + res += ri; + } + else ri=0; + } + respath = max(respath,res); + return max(le,ri); + } +}; diff --git a/Week_01/id_46/leetcode_81_046.cpp b/Week_01/id_46/leetcode_81_046.cpp new file mode 100644 index 00000000..6c6d8207 --- /dev/null +++ b/Week_01/id_46/leetcode_81_046.cpp @@ -0,0 +1,28 @@ +class Solution { +public: + bool search(vector& nums, int target) { + if(nums.size()==0) return false; + int l=0,r=nums.size()-1; + while(l<=r){ + while(l>1); + if(nums[mid]==target) return true; + else{ + if(nums[mid]=target) + l=mid+1; + else + r=mid-1; + } + else{ + if(nums[mid]>target&&nums[l]<=target) + r=mid-1; + else + l=mid+1; + } + } + } + return false; + } +}; diff --git a/Week_01/id_46/leetcode_83_046.cpp b/Week_01/id_46/leetcode_83_046.cpp new file mode 100644 index 00000000..9feee12f --- /dev/null +++ b/Week_01/id_46/leetcode_83_046.cpp @@ -0,0 +1,29 @@ +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode(int x) : val(x), next(NULL) {} + * }; + */ +class Solution { +public: + ListNode* deleteDuplicates(ListNode* head) { + if(!head || !head->next) return head; + ListNode* pre = head; + ListNode* cur = head->next; + while(cur){ + if(cur->val==pre->val){ + ListNode* tmp=cur; + pre->next=cur->next; + cur=cur->next; + delete tmp; + } + else{ + pre=cur; + cur=cur->next; + } + } + return head; + } +}; diff --git a/Week_01/id_47/LeetCode_324_47.java b/Week_01/id_47/LeetCode_324_47.java new file mode 100644 index 00000000..c0a41927 --- /dev/null +++ b/Week_01/id_47/LeetCode_324_47.java @@ -0,0 +1,27 @@ +/** + * 交叉放置大小元素 + * 时间复杂度为 O(nlog(n)) -> 排序上面 + */ +class Solution { + public void wiggleSort(int[] nums) { + if (nums.length <= 1) { + return; + } + Arrays.sort(nums); + int[] help = new int[nums.length]; + int len = nums.length; + int i = (len+1) / 2 - 1; + int j = len-1; + int k = 0; + for (; k < len; ++k) { + if ((k & 1) == 0) { + help[k] = nums[i--]; + } + else { + help[k] = nums[j--]; + } + } + + System.arraycopy(help, 0, nums, 0, help.length); + } +} \ No newline at end of file diff --git a/Week_01/id_47/LeetCode_503_47.java b/Week_01/id_47/LeetCode_503_47.java new file mode 100644 index 00000000..71f6647f --- /dev/null +++ b/Week_01/id_47/LeetCode_503_47.java @@ -0,0 +1,33 @@ +/** + * 由于题目是归属到stack目录下,因此思路会顺着stack进行。否则不一定能解答出来 + */ +class Solution { + public int[] nextGreaterElements(int[] nums) { + Stack pos = new Stack<>(); + int len = nums.length; + int[] res = new int[len]; + for (int i = 0; i < len; ++i) { + res[i] = -1; + } + for(int t=0; t<2; ++t) { + for (int i = 0; i < nums.length; ++i) { + + int num = nums[i]; + while (!pos.isEmpty() && num > nums[pos.peek()]) { + int p = pos.pop(); + res[p] = num; + } + + if (!pos.isEmpty() && pos.peek() == i) { + res[i] = -1; + break; + } + + pos.push(i); + + } + } + + return res; + } +} \ No newline at end of file diff --git a/Week_01/id_47/NOTE.md b/Week_01/id_47/NOTE.md index c684e62f..00a49759 100644 --- a/Week_01/id_47/NOTE.md +++ b/Week_01/id_47/NOTE.md @@ -1 +1,4 @@ -# 学习笔记 \ No newline at end of file +# 学习笔记 +1. 数组题目最外层的遍历是必须的。 +2. 内层的遍历一般可以优化 + 1. 查找可以为hash或者二分 \ No newline at end of file diff --git a/Week_01/id_49/LeetCode_24_49.java b/Week_01/id_49/LeetCode_24_49.java new file mode 100644 index 00000000..0bd78eb8 --- /dev/null +++ b/Week_01/id_49/LeetCode_24_49.java @@ -0,0 +1,57 @@ +package com.bugcodes.leetcode; + +/** + * Swap Nodes in Pairs + * + * @author bugcoder + */ +public class LeetCode_24_49 { + + /** + * 非递归解决两两交换 + * @param head + * @return + */ + public ListNode swapPairsIterator(ListNode head){ + //先创建一个虚拟节点,并指向头节点 + ListNode dummy = new ListNode(0); + dummy.next = head; + //创建一个游标节点cur,从dummy节点开始移动 + ListNode cur = dummy; + while (cur.next != null && cur.next.next !=null){ + //紧挨着dummy节点,再创建两个游标节点 + ListNode first = cur.next; + ListNode second = cur.next.next; + //两两交换关键逻辑 + first.next = second.next; + cur.next = second; + cur.next.next = first; + //把游标节点cur后移两位 + cur = cur.next.next; + } + return dummy.next; + } + + /** + * 递归解决两两交换 + * 把第一个节点看做一个节点,把剩余的几点看做一个节点 + * 1->2->3->4->5->6 + * 把节点1看做是一个节点A,把2->3->4->5->6这一大坨也看做是一个节点B + * @param head + * @return + */ + public ListNode swapPairsRecursion(ListNode head){ + if (head == null || head.next == null){ + return head; + } + //创建一个游标节点,指向头指针的下一个节点 + // (这个节点反转以后会顶替前一个结点,1->2交换以后2->1), + ListNode next = head.next; + //递归确定每个节点的next指针该指向哪个节点 + head.next = swapPairsRecursion(head.next.next); + //游标节点需要指向上一个节点 + next.next = head; + return next; + } + +} diff --git a/Week_01/id_49/LeetCode_81_49.java b/Week_01/id_49/LeetCode_81_49.java new file mode 100644 index 00000000..55fbefbd --- /dev/null +++ b/Week_01/id_49/LeetCode_81_49.java @@ -0,0 +1,42 @@ +package com.bugcodes.leetcode; + +/** + * Search in Rotated Sorted Array II + * + * @author bugcoder + */ +public class LeetCode_81_49 { + + public boolean search(int[] nums,int target){ + int low = 0; + int high = nums.length - 1; + int mid = 0; + while (low <= high){ + mid = low + (high - low)/2; + //如果中间的数正好是目标值,找到 + if (nums[mid] == target){ + return true; + } + //如果两边的数与中间的数相等,则同时移动左右指针 + if (nums[low] == nums[mid] && nums[high] == nums[mid]){ + ++low; + --high; + //左半段有序递增的情况下,二分查找 + }else if (nums[low] <= nums[mid]){ + if (nums[low] <= target && nums[mid] > target){ + high = mid - 1; + }else { + low = mid + 1; + } + //右半段有序递增的情况下,二分查找 + }else { + if (nums[mid] < target && nums[high] >= target){ + low = mid + 1; + }else { + high = mid - 1; + } + } + } + return false; + } +} diff --git a/Week_01/id_49/NOTE.md b/Week_01/id_49/NOTE.md index c684e62f..899fd7a0 100644 --- a/Week_01/id_49/NOTE.md +++ b/Week_01/id_49/NOTE.md @@ -1 +1,9 @@ -# 学习笔记 \ No newline at end of file +# 学习笔记 +### 链表 +关于链表的反转,常见解决方法分为**迭代和递归**。 + +**迭代**是从前到后依次处理,直到循环到链尾。 + +**递归**则相反,它是从链尾逐层返回处理一直到链首。 + +总结来说,链表的反转操作的顺序对于迭代来说就是从链头到链尾,而对于递归则是从链尾到链头。 diff --git a/Week_01/id_49/Swap_Nodes_in_Pairs.jpeg b/Week_01/id_49/Swap_Nodes_in_Pairs.jpeg new file mode 100644 index 00000000..8a0a40cf Binary files /dev/null and b/Week_01/id_49/Swap_Nodes_in_Pairs.jpeg differ diff --git a/Week_01/id_50/LeetCode_24_50.java b/Week_01/id_50/LeetCode_24_50.java new file mode 100644 index 00000000..9613a887 --- /dev/null +++ b/Week_01/id_50/LeetCode_24_50.java @@ -0,0 +1,54 @@ +package testForLC24; + +import testForLC24.LC24; +import testForLC24.ListNode; + +public class LC24 { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + + ListNode node1 = new ListNode(1); + ListNode node2 = new ListNode(2); + ListNode node3 = new ListNode(3); + ListNode node4 = new ListNode(4); + ListNode node5 = new ListNode(5); + ListNode node6 = new ListNode(6); + + node1.next = node2; + node2.next = node3; + node3.next = node4; + node4.next = node5; + node5.next = node6; + LC24 lc = new LC24(); + ListNode res = lc.swapPairs(node1); + while(res != null) { + System.out.println(res.val); + res = res.next; + } + } + + + public ListNode swapPairs(ListNode head) { + if(null == head || null == head.next) return head; + ListNode res = head.next; + ListNode current = head; + ListNode next = head.next; + ListNode temp = null; + ListNode pre = head.next; + while( current !=null && current.next != null){ + temp = current.next.next; + next = current.next; + + pre.next = next; + next.next = current; + current.next = temp; + + pre = current; + current = temp; + } + return res; + } + +} diff --git a/Week_01/id_50/LeetCode_83_50.java b/Week_01/id_50/LeetCode_83_50.java new file mode 100644 index 00000000..3133e027 --- /dev/null +++ b/Week_01/id_50/LeetCode_83_50.java @@ -0,0 +1,42 @@ +package testForLC83; + +public class LC83 { + + public static void main(String[] args) { + // TODO Auto-generated method stub + + ListNode node1 = new ListNode(1); + ListNode node2 = new ListNode(1); + ListNode node3 = new ListNode(1); + ListNode node4 = new ListNode(1); + ListNode node5 = new ListNode(2); + ListNode node6 = new ListNode(3); + + node1.next = node2; + node2.next = node3; + node3.next = node4; + node4.next = node5; + node5.next = node6; + LC83 lc = new LC83(); + lc.deleteDuplicates(node1); + while(node1 != null) { + System.out.println(node1.val); + node1 = node1.next; + } + } + +// class Solution { + public ListNode deleteDuplicates(ListNode head) { + ListNode current = head; + while(null != current.next && null != current){ + if(current.val == current.next.val){ + current.next = current.next.next; + }else{ + current = current.next; + } + } + return head; + } +// } + +} diff --git a/Week_01/id_52/LeetCode_142_52.java b/Week_01/id_52/LeetCode_142_52.java new file mode 100644 index 00000000..e4cd495d --- /dev/null +++ b/Week_01/id_52/LeetCode_142_52.java @@ -0,0 +1,33 @@ +/** + * Definition for singly-linked list. + * class ListNode { + * int val; + * ListNode next; + * ListNode(int x) { + * val = x; + * next = null; + * } + * } + */ +public class Solution { + public ListNode detectCycle(ListNode head) { + if(head==null||head.next==null){ + return null; + } + ListNode slow=head; + ListNode fast=head; + while(fast.next!=null&&fast.next.next!=null){ + slow=slow.next; + fast=fast.next.next; + if(fast==slow){ + fast=head; + while(fast!=slow){ + slow=slow.next; + fast=fast.next; + } + return fast; + } + } + return null; + } +} diff --git a/Week_01/id_52/LeetCode_20_52.java b/Week_01/id_52/LeetCode_20_52.java new file mode 100644 index 00000000..75e3a959 --- /dev/null +++ b/Week_01/id_52/LeetCode_20_52.java @@ -0,0 +1,62 @@ +class Solution { + public boolean isValid(String s) { + if(s==null){ + return true; + } + char[] chars= s.toCharArray(); + int num1 = 0; + int num2 = 0; + int num3 = 0; + for(int i=0;inums[i]){ + result[i]=nums[j]; + break; + } + if(k==nums.length-1){ + result[i]=-1; + break; + } + j++; + } + } + return result; + } +} diff --git a/Week_01/id_52/LeetCode_687_52.java b/Week_01/id_52/LeetCode_687_52.java new file mode 100644 index 00000000..23a85c5d --- /dev/null +++ b/Week_01/id_52/LeetCode_687_52.java @@ -0,0 +1,49 @@ +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +class Solution { + int max =0; + public int longestUnivaluePath(TreeNode root) { + if(root==null){ + return 0; + } + maxL(root); + return max; + } + + public int maxL(TreeNode root){ + int leftL=0; + int rightL=0; + + if(root.left!=null){ + if(root.left.val==root.val){ + leftL=1+maxL(root.left); + }else{ + maxL(root.left); + } + } + if(root.right!=null){ + if(root.right.val==root.val){ + rightL=1+maxL(root.right); + }else{ + maxL(root.right); + } + } + if((rightL+leftL)>max){ + max=rightL+leftL; + } + int result=0; + if(rightL>leftL){ + result=rightL; + }else{ + result=leftL; + } + return result; + } +} diff --git a/Week_01/id_52/LeetCode_83_52.java b/Week_01/id_52/LeetCode_83_52.java new file mode 100644 index 00000000..eb0c7c1b --- /dev/null +++ b/Week_01/id_52/LeetCode_83_52.java @@ -0,0 +1,24 @@ +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode(int x) { val = x; } + * } + */ +class Solution { + public ListNode deleteDuplicates(ListNode head) { + ListNode node= head; + if(head == null){ + return null; + } + while(node.next!=null){ + if(node.next.val==node.val){ + node.next=node.next.next; + continue; + } + node=node.next; + } + return head; + } +} diff --git a/Week_01/id_52/LeetCode_895_52.java b/Week_01/id_52/LeetCode_895_52.java new file mode 100644 index 00000000..9001476d --- /dev/null +++ b/Week_01/id_52/LeetCode_895_52.java @@ -0,0 +1,42 @@ +class FreqStack { + int max; + Map> map; + Map map2; + public FreqStack() { + max = 0; + map=new HashMap(); + map2=new HashMap(); + } + + public void push(int x) { + map2.put(x,map2.getOrDefault(x, 0)+1); + int xCount=map2.get(x); + if(max s = new Stack(); + s.push(x); + map.put(xCount,s); + } + } + + public int pop() { + int val=map.get(max).pop(); + map2.put(val,map2.get(val)-1); + if(map.get(max).size()==0){ + max--; + } + return val; + } +} + +/** + * Your FreqStack object will be instantiated and called as such: + * FreqStack obj = new FreqStack(); + * obj.push(x); + * int param_2 = obj.pop(); + */ diff --git a/Week_01/id_52/LeetCode_905_52.java b/Week_01/id_52/LeetCode_905_52.java new file mode 100644 index 00000000..65e50d24 --- /dev/null +++ b/Week_01/id_52/LeetCode_905_52.java @@ -0,0 +1,17 @@ +class Solution { + public int[] sortArrayByParity(int[] A) { + int[] result=new int[A.length]; + int j=0; + int k=A.length-1; + for(int i=0;i bool: + a = {')': '(', ']': '[', '}': '{'} + l = [None] + # 遍历s + for i in s: + print(l) + # 判断如果i在a中并且比如说是},那么如果i是否等于{(前部分也就是字典的key) 如果是就pop,如果不是就写入l + if i in a and a[i] == l[-1]: + l.pop() + else: + l.append(i) + return len(l) == 1 \ No newline at end of file diff --git a/Week_01/id_55/LeetCode_21_55.py b/Week_01/id_55/LeetCode_21_55.py new file mode 100644 index 00000000..912cdac1 --- /dev/null +++ b/Week_01/id_55/LeetCode_21_55.py @@ -0,0 +1,68 @@ +# Definition for singly-linked list. +class ListNode: + def __init__(self, x): + self.val = x + self.next = None + + +class Solution: + def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: + cur1, cur2 = l1, l2 + new = ListNode(0) + cur = new + while cur1 != None and cur2 != None: + # print(cur1.val) + # print(cur2.val) + if cur1.val <= cur2.val: + cur.next = cur1 + cur1 = cur1.next + else: + cur.next = cur2 + cur2 = cur2.next + cur = cur.next + + # 循环有先后最后会有一个数组没有循环完另一个空了,剩下就继续写入cur即可 + if cur1 != None: + cur.next = cur1 + + if cur2 != None: + cur.next = cur2 + + return new.next + + # 递归的方法 + def recursionMergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: + if not l1: return l2 + if not l2: return l1 + if l1.val < l2.val: + l1.next = self.mergeTwoLists(l1.next, l2) + return l1 + else: + l2.next = self.mergeTwoLists(l1, l2.next) + return l2 + + +# 创建链表 +a = ListNode(1) +b = ListNode(3) +c = ListNode(5) +d = ListNode(5) +e = ListNode(7) +a.next = b +b.next = c +c.next = d +d.next = e + +f = ListNode(2) +g = ListNode(2) +h = ListNode(4) +i = ListNode(6) +l = ListNode(8) +f.next = g +g.next = h +h.next = i +i.next = l +# 实例化 +demo = Solution() +# print(demo.mergeTwoLists(a, f)) +print(demo.recursionMergeTwoLists(a, f)) \ No newline at end of file diff --git a/Week_01/id_55/LeetCode_242_55.py b/Week_01/id_55/LeetCode_242_55.py new file mode 100644 index 00000000..5e86fdc6 --- /dev/null +++ b/Week_01/id_55/LeetCode_242_55.py @@ -0,0 +1,17 @@ +class Solution: + def isAnagram(self, s: str, t: str) -> bool: + if len(s) != len(t): + return False + s_array, t_array = [0]*26, [0]*26 + for letter in s: + s_array[ord(letter)-97] += 1 + for letter in t: + t_array[ord(letter)-97] += 1 + return s_array == t_array + + +s = "anagram" +t = "nagaram" +# 实例化 +demo = Solution() +print(demo.isAnagram(s, t)) \ No newline at end of file diff --git a/Week_01/id_55/LeetCode_83_55.py b/Week_01/id_55/LeetCode_83_55.py new file mode 100644 index 00000000..c69a3bb5 --- /dev/null +++ b/Week_01/id_55/LeetCode_83_55.py @@ -0,0 +1,32 @@ +# Definition for singly-linked list. +class ListNode: + def __init__(self, x): + self.val = x + self.next = None + + +class Solution: + def deleteDuplicates(self, head: ListNode) -> ListNode: + cur = head + while cur: + if cur.next and cur.val == cur.next.val: + cur.next = cur.next.next + else: + cur = cur.next + return head + + +# 创建链表 +a = ListNode(1) +b = ListNode(2) +c = ListNode(3) +d = ListNode(3) +e = ListNode(4) +a.next = b +b.next = c +c.next = d +d.next = e + +# 实例化 +demo = Solution() +print(demo.deleteDuplicates(a)) \ No newline at end of file diff --git a/Week_01/id_55/LeetCode_905_55.py b/Week_01/id_55/LeetCode_905_55.py new file mode 100644 index 00000000..afa7b33f --- /dev/null +++ b/Week_01/id_55/LeetCode_905_55.py @@ -0,0 +1,9 @@ +class Solution: + def sortArrayByParity(self, A: List[int]) -> List[int]: + a, b = [], [] + for val in A: + if val % 2 == 0: + a.append(val) + else: + b.append(val) + return a+b \ No newline at end of file diff --git a/Week_01/id_55/LeetCode_922_55.py b/Week_01/id_55/LeetCode_922_55.py new file mode 100644 index 00000000..5cbe8734 --- /dev/null +++ b/Week_01/id_55/LeetCode_922_55.py @@ -0,0 +1,16 @@ +class Solution: + def sortArrayByParityII(self, A): + a, b = [], [] + for val in A: + if val % 2 == 0: + a.append(val) + else: + b.append(val) + c, d = 0, 0 + for c in A: + A[c] = a[d] + A[c+1] = a[d] + c += 1 + d += 2 + + return a+b \ No newline at end of file diff --git a/Week_01/id_57/leetcode_21_057.cpp b/Week_01/id_57/leetcode_21_057.cpp new file mode 100644 index 00000000..fddc37bf --- /dev/null +++ b/Week_01/id_57/leetcode_21_057.cpp @@ -0,0 +1,53 @@ +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode(int x) : val(x), next(NULL) {} + * }; + */ +// 递归方法 +class Solution { +public: + ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { + if (l1 == NULL) return l2; + if (l2 == NULL) return l1; + if (l1->val < l2->val) + { + l1->next = mergeTwoLists(l1->next,l2); + return l1; + } + else + { + l2->next = mergeTwoLists(l1,l2->next); + return l2; + } + + } +}; + +// 二级指针方法 +class Solution { +public: + ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { + ListNode *head = NULL; + ListNode **pCur = &head; + while(l1 !=NULL && l2 != NULL) + { + if(l1->val < l2->val) + { + *pCur = l1; + l1 = l1->next; + } + else + { + *pCur = l2; + l2 = l2->next; + } + pCur = &(*pCur)->next; + } + *pCur = (l1 != NULL ? l1 : l2); + return head; + + } +}; \ No newline at end of file diff --git a/Week_01/id_57/leetcode_83_057.cpp b/Week_01/id_57/leetcode_83_057.cpp new file mode 100644 index 00000000..1f092f3e --- /dev/null +++ b/Week_01/id_57/leetcode_83_057.cpp @@ -0,0 +1,82 @@ +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode(int x) : val(x), next(NULL) {} + * }; + */ +class Solution { +public: + ListNode* deleteDuplicates(ListNode* head) { + ListNode* cur = head; + while (cur != NULL && cur->next != NULL) + { + if(cur->val == cur->next->val) + { + cur->next = cur->next->next; + continue; + } + cur = cur->next; + } + return head; + } +}; + + +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode(int x) : val(x), next(NULL) {} + * }; + * 无序链表处理 + */ +class Solution { +public: + ListNode* deleteDuplicates(ListNode* head) { + ListNode* res = head; + ListNode* pre = NULL; + ListNode* cur = head; + ListNode* next = NULL; + int i = 0; + unordered_map M; + if (cur == NULL || cur->next == NULL) + return res; + next = cur->next; + M[cur->val] = i++; + while(next != NULL) + { + if (M.find(next->val) == M.end()) + { + M[next->val] = i++; + pre = cur; + cur = next; + next = next->next; + printf("i %d\n",i); + } + else + { + if(pre) + { + if (res ==cur) + res = next; + pre->next = next; + cur = next; + next = next->next; + } + else + { + res = next; + pre = cur; + cur = next; + next = next->next; + printf("res: %d\n",res->val); + } + } + } + return res; + + } +}; \ No newline at end of file diff --git a/Week_01/id_58/LeetCode_21_058.java b/Week_01/id_58/LeetCode_21_058.java new file mode 100644 index 00000000..f8d3010e --- /dev/null +++ b/Week_01/id_58/LeetCode_21_058.java @@ -0,0 +1,61 @@ +package algorithm.Week_01.id_58; + +import com.sun.org.apache.xpath.internal.WhitespaceStrippingElementMatcher; + +/** + * 21. Merge Two Sorted Lists + * Merge two sorted linked lists and return it as a new list. + * The new list should be made by splicing together the nodes of the first two lists.* + * 分析: + * 由于是排好序的,直接用归并排序的算法即可 + * @auther: guangjun.ma + * @date: 2019/4/18 10:33 + * @version: 1.0 + */ +public class LeetCode_21_058 { + + public class ListNode { + int val; + ListNode next; + ListNode(int x) { val = x; } + } + + class Solution { + public ListNode mergeTwoLists(ListNode l1, ListNode l2) { + //创建一个虚拟头结点 + ListNode dummyHead = new ListNode(0); + //声明一个当前操作指针 + ListNode current = dummyHead; + + //当两个链表都不为空 + while (l1 != null && l2 != null){ + //从第一个链表l1取值,从第二个链表l2取值,如果小于l1值小,则加入到新的链表中 + if (l1.val < l2.val){ + current.next = l1; + //各后移一位,两个操作可以互换,不影响 + //l1后移 + //current当前指针后移 + l1 = l1.next; + current = current.next; + }else{ + //如果l1的值大,则将l2加入到新链表中 + current.next = l2; + l2 = l2.next; + current = current.next; + } + } + + //如果都插入完毕后,发现还有剩余的元素,则把剩下的元素全部,连接到新的链表中 + if (l1 == null){ + current.next = l2; + }else{ + current.next = l1; + } + //返回链表头结点 + //注意这里是dummyHead.next,虚拟结点的下一个结点 + return dummyHead.next; + } + } + + +} diff --git a/Week_01/id_58/LeetCode_24_058.java b/Week_01/id_58/LeetCode_24_058.java new file mode 100644 index 00000000..5a94c1dd --- /dev/null +++ b/Week_01/id_58/LeetCode_24_058.java @@ -0,0 +1,85 @@ +package algorithm.Week_01.id_58; + +/** + * 24. Swap Nodes in Pairs + * Given a linked list, swap every two adjacent nodes and return its head. + * + * You may not modify the values in the list's nodes, only nodes itself may be changed. + * Example: + * Given 1->2->3->4, you should return the list as 2->1->4->3. + * + *分析:这里主要考察就是链表的指针操作,需要用三个指针操作,注意这里需要做的就每次跳步是2步!! + * 1-2 3-4 5-6,即 cur先指向1 然后指向3,以此类推。。 + * @auther: guangjun.ma + * @date: 2019/4/18 13:04 + * @version: 1.0 + */ +public class LeetCode_24_058 { + + public class ListNode { + int val; + ListNode next; + ListNode(int x) { val = x; } + } + + class Solution { + public ListNode swapPairs(ListNode head) { + //定义一个虚拟结点 + ListNode dummy = new ListNode(-1); + //定义一个前结点指针 pre + ListNode pre = null; + //定义一个当前结点指针 cur + ListNode cur = null; + + //初始化位置 + //让虚拟结点和head结点链接,最后直接返回虚拟结点的下一个结点即是头结点 + dummy.next = head; + //pre的初始位置,是当前虚拟结点, + // 即当前结点的前面的结点, + // 即操作的两个结点的前面的一个结点,来维护操作的两个结点和前面结点的关系的 + pre = dummy; + //当前结点,指向当前操作的两个结点中的第一个结点,初始化是dummy.next,即head头结点 + // 也可以写为cur = head; + cur = dummy.next; + + //这里是核心操作!!! + // 判断条件是结点非空,当前结点的后的一个结点非空, + // 即保证操作的元素必须是两个结点的单位,1-2 3-4 + // 如果是只有一个结点,则不操作, + // 如果是空结点也不操作 + while(cur != null && cur.next != null){ + //声明一个last结点指针,主要是操作两个两个结点的后一个结点, + // last的初始位置是cur的下一个结点 + ListNode last = cur.next; + //当前结点的next指针指向last的下一个元素,即cur结点的下一个结点的指针变化为第三个元素 + //假设初始结点是0- 1 - 2 - 3 - 4 ,现在是 0-1-3-4 2 + // 2结点的位置保存在last中 + cur.next = last.next; + //last结点的next指针变成了当前结点 ,现在是 2-1 + //还有上一个步骤结果 0-1-3-4 + // 0-1-3-4 + // \ + // 2 + last.next = cur; + //现在就是要链接两个片段 + //pre结点的next指向了last结点,即虚拟结点指向了2结点 0-2-1 即0-2-1-3-4 + //这样就完成了1 2 结点的位置互换 + // 1-3-4 + // \ + // 2 + // \ + // 0 + pre.next = last; + + //接下来就是移动元素,开始操作3 、4元素 + //pre指向当前结点,cur=1 + //注意这里不是往后移了一位而是两位, pre指向了0-2-1-3-4 中的1 + pre = cur; + //cur指针后移一位,就是3。这样就开始了以3-4为操作单元的的操作单元 + cur = cur.next; + } + + return dummy.next; + } + } +} diff --git a/Week_01/id_58/LeetCode_83_058.java b/Week_01/id_58/LeetCode_83_058.java new file mode 100644 index 00000000..f34a3c9d --- /dev/null +++ b/Week_01/id_58/LeetCode_83_058.java @@ -0,0 +1,57 @@ +package algorithm.Week_01.id_58; + +/** + * + * 83. Given a sorted linked list, delete all duplicates such that each element appear only once. + * + * Example 1: + * + * Input: 1->1->2 + * Output: 1->2 + * Example 2: + * + * Input: 1->1->2->3->3 + * Output: 1->2->3 + * 分析: + * 这里是一个排好序的数组,这样的话,我们就省掉了很多的事情, + * 只要拿一个元素和他后边的元素比较即可,如果相同则next指针指向它后边的元素, + * 如果不相同,则接着考察下一个元素 + * + * @auther: guangjun.ma + * @date: 2019/4/17 17:36 + * @version: 1.0 + */ +public class LeetCode_83_058 { + + /** + * ListNode节点定义 + */ + public class ListNode { + int val; + ListNode next; + ListNode(int x) { val = x; } + } + + class Solution { + public ListNode deleteDuplicates(ListNode head) { + //1、定义一个current指针,用于操作当前元素 + //head指针不动,只是记录链表头结点 + ListNode current = head; + //当前节点非空,当前结点的下一个结点也不为空,即不是空结点也不是最后的结点 + while (current != null && current.next != null){ + //当前节点等于下一个结点的值 + if (current.val == current.next.val){ + //当前结点的next指针,指向当前结点的下一个结点的下一个结点 + //即next指针掉过一个结点,指向它后边的一个结点 + current.next = current.next.next; + }else{ + //如果不相等,接着考察下一个元素,current指针后移一位 + current = current.next; + } + } + //返回头结点 + return head; + } + } + +} diff --git a/Week_01/id_58/NOTE.md b/Week_01/id_58/NOTE.md index c684e62f..1f0a50a7 100644 --- a/Week_01/id_58/NOTE.md +++ b/Week_01/id_58/NOTE.md @@ -1 +1,17 @@ -# 学习笔记 \ No newline at end of file +# 学习笔记 +本周的学习总结: +1、学会了GitHub的pull-requet的使用。平时我们都是直接用git提交,然后merge到master, +对于github的pull-request的提交形式不太熟悉,通过微信群咨询和同学的帮助,我学会了 +这项功能的使用。 +2、另外感触比较深的如何结合工作和学习任务,本周共布置了16道题,我完成了3道题目。 +虽然完成了,但是还是与之前的心里目标相差很远,希望在接下来的一周,能够每天按质 +按量的完成学习任务。 +3、本周主要学习了链表的功能使用 + 83题:删除链表中的所有重复元素 + 21题:合并两个排序的链表的链表 + 24题:交换两个相邻的结点 +4、通过上面题目的训练,我对链表的题目有了新的认识,对于链表题目的解题方法就是要 +借助画图,拿出笔,简单的画出操作的关系,就可以很好的维护好各个结点关系,避免各种 +找不到后续结点错误。 +5、对于后续的数组、栈、递归、排序的题目,在后续的过程中也要快速完成。 + diff --git a/Week_01/id_58/TestClass.java b/Week_01/id_58/TestClass.java new file mode 100644 index 00000000..6aa207a5 --- /dev/null +++ b/Week_01/id_58/TestClass.java @@ -0,0 +1,12 @@ +package algorithm.Week_01.id_58; + +public class TestClass { + + public static void main(String[] args) { + + System.out.println("Hello World!" + + ); + } + +} diff --git a/Week_01/id_59/LeetCode_905_059.py b/Week_01/id_59/LeetCode_905_059.py new file mode 100644 index 00000000..c38d079d --- /dev/null +++ b/Week_01/id_59/LeetCode_905_059.py @@ -0,0 +1,14 @@ +class Solution: + def sortArrayByParity(self, A: List[int]) -> List[int]: + low, high = 0, len(A) - 1 + while low < high: + if A[low] % 2 > A[high] % 2: + A[low], A[high] = A[high], A[low] + + if A[low] % 2 == 0: + low += 1 + + if A[high] % 2 == 1: + high -= 1 + + return A \ No newline at end of file diff --git a/Week_01/id_59/LeetCode_922_059.py b/Week_01/id_59/LeetCode_922_059.py new file mode 100644 index 00000000..17d810bd --- /dev/null +++ b/Week_01/id_59/LeetCode_922_059.py @@ -0,0 +1,9 @@ +class Solution: + def sortArrayByParityII(self, A: List[int]) -> List[int]: + even = 1 + for odd in range(0, len(A), 2): + if A[odd] % 2: + while A[even] % 2: + even += 2 + A[odd], A[even] = A[even], A[odd] + return A \ No newline at end of file diff --git a/Week_01/id_59/NOTE.md b/Week_01/id_59/NOTE.md index c684e62f..d864abd1 100644 --- a/Week_01/id_59/NOTE.md +++ b/Week_01/id_59/NOTE.md @@ -1 +1,2 @@ -# 学习笔记 \ No newline at end of file +# 学习笔记 +在老师讲课的过程中,以及自己实践的过程中发现,双指针(python中类似的双变量)在算法解体过程中是非常有用的。 \ No newline at end of file diff --git a/Week_01/id_6/LeetCode_20_6.java b/Week_01/id_6/LeetCode_20_6.java new file mode 100644 index 00000000..307268ca --- /dev/null +++ b/Week_01/id_6/LeetCode_20_6.java @@ -0,0 +1,51 @@ + + + + // 利用栈实现括号匹配检查 + // 左括号入栈,右括号出栈 + public boolean isValid2(String s) { + if (s.length() == 0){ + return true; + } + + if (s.length() == 1){ + return false; + } + + Stack stack = new Stack(); + + char c = '0'; + char d = '0'; + + // 遍历str + for (int i = 0; i < s.length() ; i++) { + c = s.charAt(i); + if (c=='(' || c=='{' || c=='['){ + // 入栈时,压入对应的右括号,减少出栈时比对的复杂度 + if (c == '('){ + stack.push(')'); + }else if (c == '{'){ + stack.push('}'); + }else { + stack.push(']'); + } + } + + if (c==')' || c=='}' || c==']'){ + if (stack.isEmpty()){ + return false; + } + + d = (char)stack.pop(); + if (c != d){ + return false; + } + } + } + // 栈应该是空 + if (!stack.empty()){ + return false; + } + + return true; + } \ No newline at end of file diff --git a/Week_01/id_6/LeetCode_21_6.java b/Week_01/id_6/LeetCode_21_6.java new file mode 100644 index 00000000..05e101e3 --- /dev/null +++ b/Week_01/id_6/LeetCode_21_6.java @@ -0,0 +1,42 @@ + + + // ͨȽϣIJ뵽µ + // ڱڵ㣬ٴ븴Ӷ + public ListNode mergeTwoLists2(ListNode l1, ListNode l2) { + System.out.println("mergeTwoLists2"); + if (l1 == null){ + return l2; + } + if (l2 == null){ + return l1; + } + + // ڱڵ + ListNode temp = new ListNode(0); + ListNode head = temp; + ListNode tail = temp; + // ıԭʼ + ListNode current1 = l1; + ListNode current2 = l2; + while (current1 != null && current2 != null){ + // ˭С˭ + if (current1.val <= current2.val){ + tail.next = current1; + tail = current1; + current1 = current1.next; + } + else { + tail.next = current2; + tail = current2; + current2 = current2.next; + } + } + // ʣб + if (current1 == null){ + tail.next = current2; + }else { + tail.next = current1; + } + + return head.next; + } \ No newline at end of file diff --git a/Week_01/id_6/LeetCode_242_6.java b/Week_01/id_6/LeetCode_242_6.java new file mode 100644 index 00000000..35e0ab0e --- /dev/null +++ b/Week_01/id_6/LeetCode_242_6.java @@ -0,0 +1,46 @@ + + +// LeetCode 242 + public boolean isAnagram(String s, String t) { + + // 两个字符串长度必须相等 + int sLen = s.length(); + int tLen = t.length(); + + if (sLen != tLen){ + return false; + } + + // s存入hash表,<字符, 次数> + HashMap map = new HashMap<>(); + for (int i = 0; i < sLen; i++) { + char a = s.charAt(i); + if (map.containsKey(a)){ + map.put(a, map.get(a)+1); + }else { + map.put(a, 1); + } + } + + + // 遍历t,在hash表查找每个字符 + for (int i = 0; i < tLen; i++) { + char a = t.charAt(i); + if (map.containsKey(a)){ + // 次数-1 + int n = map.get(a); + if (n-1 > 0) { + map.put(a, n-1); + }else { + map.remove(a); + } + } + else { + return false; + } + } + + return true; + } + + \ No newline at end of file diff --git a/Week_01/id_6/LeetCode_324_6.java b/Week_01/id_6/LeetCode_324_6.java new file mode 100644 index 00000000..46a86517 --- /dev/null +++ b/Week_01/id_6/LeetCode_324_6.java @@ -0,0 +1,35 @@ + + + + // żԪ Ԫ + // [1, 6, 1, 5, 1, 4] [2, 6, 1, 5, 1] + // С С С С С С + // ҪĸʽҪȻֳɴС + // ԪʱСDzҪһԪ + public void wiggleSort(int[] nums) { + int len = nums.length; + + if (len == 0){ + return; + } + // + int[] rst = Arrays.copyOf(nums, len); + Arrays.sort(rst); + for (int i = 0; i < len; i++) { + nums[i] = 0; + } + + // ȡֵʼλ + int big = 0; + if (len % 2 == 0){ + big = len / 2; + }else { + big = len / 2 + 1; + nums[len-1] = rst[0]; + } + // ÿηֱӴСȡһд + // [4,5,5,6] ֱֵǰ濪ʼȡԴӺǰȡ + for (int i = 0; i < len - big; i++) { + nums[i*2] = rst[big - 1 - i]; + nums[i*2+1] = rst[len -1 - i]; + } \ No newline at end of file diff --git a/Week_01/id_6/LeetCode_441_6.java b/Week_01/id_6/LeetCode_441_6.java new file mode 100644 index 00000000..34f94dca --- /dev/null +++ b/Week_01/id_6/LeetCode_441_6.java @@ -0,0 +1,21 @@ + + + // 怎么用二分法没想通 ?? + + + public int arrangeCoins(int n) { + if (n == 0){ + return 0; + } + + // 循环分解,直到剩余数量 < 分解次数+1 + int i = 0; + for (i = 1; i < n; i++) { + n -= i; + if (n < i + 1){ + break; + } + } + + return i; + } \ No newline at end of file diff --git a/Week_01/id_6/LeetCode_503_6.java b/Week_01/id_6/LeetCode_503_6.java new file mode 100644 index 00000000..f78b59d8 --- /dev/null +++ b/Week_01/id_6/LeetCode_503_6.java @@ -0,0 +1,75 @@ + + + + // LeetCode 503 + // 遍历数组,每个数都和其后面的数据比较,直到循环回到自己的位置 + // 100, 1, 11, 1, 110, 109 + // 当前值 小 小 小 大 + // 那么[当前值 -> 110] 之间的数据,都应该用110替换。 + // 可以用栈来暂存这些数据。栈空表明区间内的所有数据都替换完成 + + // 由于我们是替换数据,所以栈中存的应该是元素的索引值 + + // 取一个元素,如果该元素比栈顶元素小,直接压栈 + // 如果比栈顶元素大,则开始替换栈中元素。最后将该元素压栈 + public int[] nextGreaterElements2(int[] nums) { + Stack stack = new Stack<>(); + int len = nums.length; + int[] rst = new int[len]; + Arrays.fill(rst, -1); + + // 由于是循环数组,遍历时长度取2*len + // 长度超过len时,不再入栈 + for (int i = 0; i < 2 * len; i++) { + int ii = i % len; + // 出栈条件判断 + while (!stack.isEmpty() && nums[ii] > nums[stack.peek()]) { + rst[stack.pop()] = nums[ii]; + } + + // 入栈条件判断 + // 由于当前元素可能导致出栈操作,所以要等出栈完成后,再做入栈判断 + if (i < len){ + stack.push(ii); + } + } + + return rst; + } + + + public int[] nextGreaterElements(int[] nums) { + Stack stack = new Stack<>(); + int len = nums.length; + int[] rst = new int[len]; + Arrays.fill(rst, -1); + + // 由于是循环数组,遍历时长度取2*len + for (int i = 0; i < 2 * len; i++) { + int ii = i % len; + // 出栈条件判断 + if (!stack.isEmpty() && nums[ii] > nums[stack.peek()]) { + while (!stack.isEmpty()) { + // 当前值不再大于栈顶值结束出栈 + if (nums[ii] <= nums[stack.peek()]){ + break; + } + rst[stack.pop()] = nums[ii]; + } + } + // 入栈条件判断 + // 由于当前元素可能导致出栈操作,所以要等出栈完成后,再做入栈判断 + if (i < len && stack.isEmpty()) { + stack.push(ii); + continue; + } + if (!stack.isEmpty() && nums[ii] <= nums[stack.peek()]) { + if (i < len) { + stack.push(ii); + } + } + + } + + return rst; + } \ No newline at end of file diff --git a/Week_01/id_6/LeetCode_50_6.java b/Week_01/id_6/LeetCode_50_6.java new file mode 100644 index 00000000..e3794d5f --- /dev/null +++ b/Week_01/id_6/LeetCode_50_6.java @@ -0,0 +1,36 @@ + + + + // 把幂次方n除2,结果就是两个幂次方是n/2的数的相乘,这样只需要计算1次n/2次方的运算 + // 依次类推,直到指数变为1,不能再分 + // 如果指数为奇数,二分之后,计算结果时需要多乘一次x + // LeetCode提交,报栈溢出 + public double myPow1(double x, int n) { + // 递归出口 + if (n == 0){ + return 1; + } + if (n == 1){ + return x; + } + // 指数是负数 + if (n == -1){ + return 1/x; + } + + // 计算n/2次方 + double rst = myPow(x, n/2); + // 计算n次方 + rst = rst * rst; + // 奇次方需要多乘一次 + if (n % 2 != 0){ + if (n > 0){ + rst *= x; + }else { + rst *= 1/x; + } + + } + + return rst; + } \ No newline at end of file diff --git a/Week_01/id_6/LeetCode_687_6.java b/Week_01/id_6/LeetCode_687_6.java new file mode 100644 index 00000000..ca16a76b --- /dev/null +++ b/Week_01/id_6/LeetCode_687_6.java @@ -0,0 +1,32 @@ + + + + public int longestUnivaluePath(TreeNode root) { + return longestPath(root); + } + + + public int longestPath(TreeNode node){ + if (node == null){ + return 0; + } + + // 节点值与左右子节点值相同,路径=左+右+2 + if (node.left!=null && node.right!=null && node.val==node.left.val && node.val==node.right.val){ + return longestPath(node.left) + longestPath(node.right) + 2; + } + + // 节点值与左子节点值相同,路径=max(左+1, 右) + if (node.left!=null && node.val==node.left.val){ + return Math.max(longestPath(node.left)+1, longestPath(node.right)); + } + + // 节点值与右子节点值相同,路径=max(左, 右+1) + if (node.right!=null && node.val==node.right.val){ + return Math.max(longestPath(node.right)+1, longestPath(node.left)); + } + + // 节点值与左右子节点值都不相同,路径=max(左,右) + return Math.max(longestPath(node.left), longestPath(node.right)); + + } \ No newline at end of file diff --git a/Week_01/id_6/LeetCode_83_6.java b/Week_01/id_6/LeetCode_83_6.java new file mode 100644 index 00000000..677be5f6 --- /dev/null +++ b/Week_01/id_6/LeetCode_83_6.java @@ -0,0 +1,37 @@ + + + + public ListNode deleteDuplicates(ListNode head) { + + if (head == null){ + return head; + } + + // ȡÿڵ㣬Dzظڵ + // жϽڵǷظķ + // ÿζڵ㣬ȥhashвѯڣΪظڵ㣻򣬲hash + // hashΪ˿֧ + + HashMap map = new HashMap<>(); + + // Ľڵָ. headڵǵһȻΪظҪɾĽڵ + map.put(head.val, head.val); + + ListNode current = head.next; + // βڵ. βʱ + ListNode tail = head; + + while (current != null){ + // ûҵ˵ظڵ㣬ýڵhash + if (!map.containsKey(current.val)){ + System.out.println(current.val); + map.put(current.val, current.val); + tail.next = current; + tail = current; + } + current = current.next; + } + tail.next = null; + this.printNodes(head); + return head; + } \ No newline at end of file diff --git a/Week_01/id_6/LeetCode_905_6.java b/Week_01/id_6/LeetCode_905_6.java new file mode 100644 index 00000000..e34e300b --- /dev/null +++ b/Week_01/id_6/LeetCode_905_6.java @@ -0,0 +1,65 @@ + + // ½飬żǰ룬Ӻǰ + // ʱ临ӶO(n) + // ռ临ӶO(2n)ƻԭ + public int[] sortArrayByParity(int[] A) { + int[] B = new int[A.length]; + + int head = 0; + int tail = A.length -1; + // ݣż + for (int i = 0; i < A.length ; i++) { + if (A[i] % 2 == 0){ + B[head] = A[i]; + head ++; + }else { + B[tail] = A[i]; + tail --; + } + // ݶ + if (head > tail){ + break; + } + } + return B; + } + + + // ֱָǰɨ裬żǰ룬Ӻǰ + // 飬Լڴռ + // ʱ临ӶO(n) + // ռ临ӶO(n)ƻԭ + public int[] sortArrayByParity1(int[] A) { + if (A.length == 1){ + return A; + } + + int head = 0; + int tail = A.length -1; + int swap = 0; + // ݣż + for (int i = 0; i < A.length ; i++) { + // headָżǰ + if (A[head] % 2 == 0){ + head ++; + } + // headָβһżhead + else { + if (A[tail] % 2 != 0){ + tail --; + }else { + swap = A[head]; + A[head] = A[tail]; + A[tail] = swap; + head ++; + tail --; + } + + } + // ݶ + if (head >= tail){ + break; + } + } + return A; + } \ No newline at end of file diff --git a/Week_01/id_6/LeetCode_922_6.java b/Week_01/id_6/LeetCode_922_6.java new file mode 100644 index 00000000..5d5a3bf7 --- /dev/null +++ b/Week_01/id_6/LeetCode_922_6.java @@ -0,0 +1,21 @@ + +// 新建数组,偶数插入偶位置,奇数插入奇位置 +// 两个指针分别指向偶、奇位置 +public int[] sortArrayByParityII(int[] A) { + int[] B = new int[A.length]; + + int odd = 1; + int even = 0; + + for (int i = 0; i < A.length ; i++) { + if (A[i] % 2 == 0){ + B[even] = A[i]; + even += 2; + }else { + B[odd] = A[i]; + odd += 2; + } + } + + return B; +} \ No newline at end of file diff --git a/Week_01/id_60/LeetCode_021_060.go b/Week_01/id_60/LeetCode_021_060.go new file mode 100644 index 00000000..d4270c23 --- /dev/null +++ b/Week_01/id_60/LeetCode_021_060.go @@ -0,0 +1,45 @@ +package wee1 + +import "fmt" + +/* +输入:1->2->4, 1->3->4 +输出:1->1->2->3->4->4 +*/ + +func mergeTwoLists(l1 *ListNode, l2 *ListNode) *ListNode { + if l1==nil { + return l2 + }else if l2==nil{ + return l1 + } + c1,p1:=l1,l1 + c2,p2:=l2,l2 + + for c1!=nil && c2!=nil { + if c1.Val>c2.Val { + p2=c2 + c2=c2.Next + + if p1==c1{ + p2.Next=p1 + p1=p2 + l1=p2 + }else{ + p2.Next=c1 + p1.Next=p2 + p1=p2 + + } + }else{ + p1=c1 + c1=c1.Next + } + + } + if c1==nil{ + p1.Next=c2 + } + + return l1 +} diff --git a/Week_01/id_60/LeetCode_242_060.go b/Week_01/id_60/LeetCode_242_060.go new file mode 100644 index 00000000..74020cbf --- /dev/null +++ b/Week_01/id_60/LeetCode_242_060.go @@ -0,0 +1,26 @@ +package wee1 + +//242. 有效的字母异位词 +//valid-anagram/description +func isAnagram(s string, t string) bool { + m1, m2 := make(map[string]int, 0), make(map[string]int, 0) + for _, v := range s { + m1[string(v)]++ + } + for _, v := range t { + m2[string(v)]++ + } + for _, v := range s { + if m1[string(v)] != m2[string(v)] { + return false + } + + } + for _, v := range t { + if m1[string(v)] != m2[string(v)] { + return false + } + } + return true + +} diff --git a/Week_01/id_61/leetcode_142_061.cpp b/Week_01/id_61/leetcode_142_061.cpp new file mode 100644 index 00000000..715b8d6c --- /dev/null +++ b/Week_01/id_61/leetcode_142_061.cpp @@ -0,0 +1,32 @@ +// +// Created by 贾凯超 on 2019/4/18. +// +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode(int x) : val(x), next(NULL) {} + * }; + */ + +//#142 给定一个链表,返回链表开始入环的第一个结点。 如果链表无环,则返回 null。 +//思考:使用hashMap存放走过的记录,但会增加额外空间 +//进阶:在不破坏原链表也不使用额外空间的情况下,使用快慢指针方案。但是由于可能不是一个完整的环 +//会导致时间效率降低很多 +class Solution { +public: + ListNode *detectCycle(ListNode *head) { + map temp; + ListNode *current = head; + while (current) { + //如果存在,说明曾经走过,第一次出现的即是第一个节点 + if (temp[current]) { + return current; + } + temp[current] = 1; + current = current->next ? current->next : NULL; + } + return NULL; + } +}; diff --git a/Week_01/id_61/leetcode_503_061.cpp b/Week_01/id_61/leetcode_503_061.cpp new file mode 100644 index 00000000..67f8fd10 --- /dev/null +++ b/Week_01/id_61/leetcode_503_061.cpp @@ -0,0 +1,25 @@ +// +// Created by 贾凯超 on 2019/4/18. +// +//#503 给定一个循环数组(最后一个元素的下一个元素是数组的第一个元素), +//输出每个元素的下一个更大元素。数字 x 的下一个更大的元素是按数组遍历顺序, +//这个数字之后的第一个比它更大的数,这意味着你应该循环地搜索它的下一个更大的数。如果不存在,则输出 -1。 +//思考:该算法时间复杂度为O(n^2),需要优化,另外没有用到stack,使用取模的方式控制循环 +class Solution { +public: + vector nextGreaterElements(vector& nums) { + vector result(nums.size()); + for (int i = 0; i < nums.size(); i++) { + int j = (i + 1) % nums.size(); + result[i] = -1; + while (i != j) { + if (nums[j] > nums[i]) { + result[i] = nums[j]; + break; + } + j = (j + 1) % nums.size(); + } + } + return result; + } +}; \ No newline at end of file diff --git a/Week_01/id_62/LeetCode_242_62.c b/Week_01/id_62/LeetCode_242_62.c new file mode 100644 index 00000000..a3948d9a --- /dev/null +++ b/Week_01/id_62/LeetCode_242_62.c @@ -0,0 +1,15 @@ +bool isAnagram(char* s, char* t) { + int lens = strlen(s); + int lent = strlen(t); + if (lens != lent) return false; + int flag[26] = {0}; + for (int i = 0; i < lens; i++){ + flag[s[i] - 'a']++; + } + for (int i = 0; i < lent; i++){ + if (flag[t[i] - 'a'] == 0) return false; + flag[t[i] - 'a']--; + } + return true; +} +//4MS \ No newline at end of file diff --git a/Week_01/id_62/LeetCode_441_62.c b/Week_01/id_62/LeetCode_441_62.c new file mode 100644 index 00000000..37862825 --- /dev/null +++ b/Week_01/id_62/LeetCode_441_62.c @@ -0,0 +1,17 @@ +int arrangeCoins(int n) { + int low = 0; + int mid = 0; + int high = n; + while(low <= high) + { + mid = (low + high) / 2; + if( 0 <= n - (mid+1)*mid/2 < mid + 1) + return mid; + else if(n - (mid+1)*mid/2 >= mid + 1) + low = mid + 1; + else if(n - (mid+1)*mid/2 < 0) + high = mid - 1; + } +} + +//8ms \ No newline at end of file diff --git a/Week_01/id_63/LeetCode_141_63.java b/Week_01/id_63/LeetCode_141_63.java new file mode 100644 index 00000000..4555f24f --- /dev/null +++ b/Week_01/id_63/LeetCode_141_63.java @@ -0,0 +1,40 @@ +/* +https://leetcode-cn.com/problems/linked-list-cycle/ +给定一个链表,判断链表中是否有环。 +为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 pos 是 -1,则在该链表中没有环。 +*/ +/** + * Definition for singly-linked list. + * class ListNode { + * int val; + * ListNode next; + * ListNode(int x) { + * val = x; + * next = null; + * } + * } + */ +public class Solution { + public boolean hasCycle(ListNode head) { + if (head == null || head.next == null) { + return false; + } + boolean result = false; + ListNode node = head; + ListNode node2 = head; + while (node != null && node2 != null) { + node = node.next; + node2 = node2.next; + if (node2 == null) { + break; + } else { + node2 = node2.next; + if (node2 == node) { + result = true; + break; + } + } + } + return result; + } +} diff --git a/Week_01/id_63/LeetCode_142_63.java b/Week_01/id_63/LeetCode_142_63.java new file mode 100644 index 00000000..4e79d604 --- /dev/null +++ b/Week_01/id_63/LeetCode_142_63.java @@ -0,0 +1,47 @@ +/* +https://leetcode-cn.com/problems/linked-list-cycle-ii/ +给定一个链表,返回链表开始入环的第一个节点。 如果链表无环,则返回 null。 +为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 pos 是 -1,则在该链表中没有环。 +说明:不允许修改给定的链表。 +*/ +/** + * Definition for singly-linked list. + * class ListNode { + * int val; + * ListNode next; + * ListNode(int x) { + * val = x; + * next = null; + * } + * } + */ +public class Solution { + public ListNode detectCycle(ListNode head) { + if (head == null || head.next == null) { + return null; + } + ListNode node = head; + ListNode node2 = head; + while (true) { + node = node.next; + node2 = node2.next; + if (node2 == null) { + return null; + } else { + node2 = node2.next; + if (node2 == null) { + return null; + } + if (node2 == node) { + break; + } + } + } + node = head; + while (node != node2) { + node = node.next; + node2 = node2.next; + } + return node; + } +} diff --git a/Week_01/id_63/LeetCode_206_63.java b/Week_01/id_63/LeetCode_206_63.java new file mode 100644 index 00000000..817a898d --- /dev/null +++ b/Week_01/id_63/LeetCode_206_63.java @@ -0,0 +1,32 @@ +/* +https://leetcode-cn.com/problems/reverse-linked-list/ +反转一个单链表。 +*/ +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode(int x) { val = x; } + * } + */ +class Solution { + public ListNode reverseList(ListNode head) { + if (head == null || head.next == null) { + return head; + } + ListNode pre = null; + ListNode node = head; + ListNode next = null; + while (true) { + next = node.next; + node.next = pre; + if (next == null) { + break; + } + pre = node; + node = next; + } + return node; + } +} diff --git a/Week_01/id_63/LeetCode_21_63.java b/Week_01/id_63/LeetCode_21_63.java new file mode 100644 index 00000000..216c3d95 --- /dev/null +++ b/Week_01/id_63/LeetCode_21_63.java @@ -0,0 +1,50 @@ +/* +https://leetcode-cn.com/problems/merge-two-sorted-lists/ +将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。 +*/ +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode(int x) { val = x; } + * } + */ +class Solution { + public ListNode mergeTwoLists(ListNode l1, ListNode l2) { + if (l1 == null) { + return l2; + } + if (l2 == null) { + return l1; + } + ListNode node1 = l1; + ListNode node2 = l2; + ListNode head = null; + ListNode tail = null; + ListNode node = null; + while (node1 != null && node2 != null) { + if (node1.val <= node2.val) { + node = node1; + node1 = node1.next; + } else { + node = node2; + node2 = node2.next; + } + if (head == null) { + head = node; + } else { + tail.next = node; + } + tail = node; + } + if (node1 != null) { + tail.next = node1; + return head; + } + if (node2 != null) { + tail.next = node2; + } + return head; + } +} diff --git a/Week_01/id_63/LeetCode_83_63.java b/Week_01/id_63/LeetCode_83_63.java new file mode 100644 index 00000000..1909cfa7 --- /dev/null +++ b/Week_01/id_63/LeetCode_83_63.java @@ -0,0 +1,27 @@ +/* +https://leetcode-cn.com/problems/remove-duplicates-from-sorted-list/ +给定一个排序链表,删除所有重复的元素,使得每个元素只出现一次。 +*/ +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode(int x) { val = x; } + * } + */ +class Solution { + public ListNode deleteDuplicates(ListNode head) { + ListNode node = head; + ListNode next = null; + while (node != null) { + next = node.next; + if (next != null && node.val == next.val) { + node.next = next.next; + } else { + node = node.next; + } + } + return head; + } +} diff --git a/Week_01/id_63/NOTE.md b/Week_01/id_63/NOTE.md index c684e62f..9793ea72 100644 --- a/Week_01/id_63/NOTE.md +++ b/Week_01/id_63/NOTE.md @@ -1 +1,4 @@ -# 学习笔记 \ No newline at end of file +# 学习笔记 +## 如果题目不是特别一目了然很容易的那种,最好是先分析和画图,尤其是边界条件,这样事半功倍。 +## 根据边界条件和不同的参数组合写测试代码。 +## 如果在线写效率不高,那就用IDE写,本地测试通过后再提交。 diff --git a/Week_01/id_64/LeetCode_141_64.js b/Week_01/id_64/LeetCode_141_64.js new file mode 100644 index 00000000..a0be889a --- /dev/null +++ b/Week_01/id_64/LeetCode_141_64.js @@ -0,0 +1,51 @@ +/** + * Definition for singly-linked list. + * function ListNode(val) { + * this.val = val; + * this.next = null; + * } + */ + +/** + * 141. 环形链表 + * https://leetcode-cn.com/problems/linked-list-cycle/ + * 使用 set 标记访问过的 node + * + * @param {ListNode} head + * @return {boolean} + */ +var hasCycle = function(head) { + if (head == null || head.next == null) { return false; } + + const visitedSet = new Set(); + while (head) { + if (visitedSet.has(head)) { + return true; + } + visitedSet.add(head); + head = head.next; + } + + return false; + }; + + /** + * 141. 环形链表 + * https://leetcode-cn.com/problems/linked-list-cycle/ + * 使用快慢指针, 当快指针在环里打转碰上慢指针即检测到环 + * + * @param {ListNode} head + * @return {boolean} + */ +var hasCycle = function(head) { + let slow = head; + let fast = head; + while (fast != null) { + if (fast.next == null) { return false; } + fast = fast.next.next; + slow = slow.next; + if (fast == slow) return true; + } + + return false; + }; \ No newline at end of file diff --git a/Week_01/id_64/LeetCode_20_64.js b/Week_01/id_64/LeetCode_20_64.js new file mode 100644 index 00000000..8d281e58 --- /dev/null +++ b/Week_01/id_64/LeetCode_20_64.js @@ -0,0 +1,29 @@ +/** + * 20. 有效的括号 + * https://leetcode-cn.com/problems/valid-parentheses/ + * 通过栈,匹配左刮号进栈,匹配右刮号出栈 + * @param {string} s + * @return {boolean} + */ +var isValid = function(s) { + var stack = []; + for (var i = 0; i < s.length; i++) { + var c = s.charAt(i); + if (/\{|\[|\(/g.test(c)) { + stack.push(c); + } else { + if (!stack.length) { return false; } + var topChar = stack.pop(); + if (c == '}' && topChar != '{') { + return false; + } + if (c == ']' && topChar != '[') { + return false; + } + if (c == ')' && topChar != '(') { + return false; + } + } + } + return !stack.length; +}; \ No newline at end of file diff --git a/Week_01/id_64/LeetCode_21_64.js b/Week_01/id_64/LeetCode_21_64.js new file mode 100644 index 00000000..a7298a76 --- /dev/null +++ b/Week_01/id_64/LeetCode_21_64.js @@ -0,0 +1,65 @@ +/** + * Definition for singly-linked list. + * function ListNode(val) { + * this.val = val; + * this.next = null; + * } + */ +/** + * 21. 合并两个有序链表 + * https://leetcode-cn.com/problems/merge-two-sorted-lists/ + * + * @param {ListNode} l1 + * @param {ListNode} l2 + * @return {ListNode} + */ +var mergeTwoLists = function(l1, l2) { + const dummyHead = new ListNode(); + let curr = dummyHead; + let currL1 = l1; + let currL2 = l2; + + while(currL1 != null && currL2 != null) { + // 比较两个结点的大小,小的先加入新链表 + if (currL1.val <= currL2.val) { + curr.next = currL1; + currL1 = currL1.next; + } else { + curr.next = currL2; + currL2 = currL2.next; + } + curr = curr.next; + } + + // 如果 l1 还没遍历完直接加入新链表 + if (currL1 != null) { + curr.next = currL1; + } + // 如果 l2 还没遍历完直接加入新链表 + if (currL2 != null) { + curr.next = currL2; + } + + return dummyHead.next; +}; + +/** + * 21. 合并两个有序链表 + * https://leetcode-cn.com/problems/merge-two-sorted-lists/ + * 递归实现 + * + * @param {ListNode} l1 + * @param {ListNode} l2 + * @return {ListNode} + */ +var mergeTwoLists = function(l1, l2) { + // 返回非空的链表 + if (l1 == null || l2 == null) { return l1 ? l1 : l2; } + if (l1.val < l2.val) { + l1.next = mergeTwoLists(l1.next, l2); + return l1; + } else { + l2.next = mergeTwoLists(l2.next, l1); + return l2; + } +}; \ No newline at end of file diff --git a/Week_01/id_64/LeetCode_242_64.js b/Week_01/id_64/LeetCode_242_64.js new file mode 100644 index 00000000..45f86b10 --- /dev/null +++ b/Week_01/id_64/LeetCode_242_64.js @@ -0,0 +1,33 @@ +/** + * 242. 有效的字母异位词 + * https://leetcode-cn.com/problems/valid-anagram/ + * 使用 map 累加 s 中每个元素个数,t 递减每个元素个数,元素为零即删除,最终 map size 为 0 + * + * @param {string} s + * @param {string} t + * @return {boolean} + */ +var isAnagram = function(s, t) { + if (s.length != t.length) { return false; } + const map = new Map(); + for (let i = 0; i < s.length; i++) { + const e = s.charAt(i); + if (map.has(e)) { + map.set(e, map.get(e) + 1); + } else { + map.set(e, 1); + } + } + + for (let i = 0; i < t.length; i++) { + const e = t.charAt(i); + if (map.has(e)) { + map.set(e, map.get(e) - 1); + if (map.get(e) == 0) { + map.delete(e); + } + } + } + + return map.size == 0; +}; \ No newline at end of file diff --git a/Week_01/id_64/LeetCode_24_64.js b/Week_01/id_64/LeetCode_24_64.js new file mode 100644 index 00000000..c9e74e1f --- /dev/null +++ b/Week_01/id_64/LeetCode_24_64.js @@ -0,0 +1,51 @@ +/** + * Definition for singly-linked list. + * function ListNode(val) { + * this.val = val; + * this.next = null; + * } + */ +/** + * 24. 两两交换链表中的节点 + * https://leetcode-cn.com/problems/swap-nodes-in-pairs/ + * 迭代实现 + * 交换: prev.next -> curr.next; curr.next.next -> curr; curr.next = curr.next.next; + * 移动: prev = curr; curr = curr.next; + * + * @param {ListNode} head + * @return {ListNode} + */ +var swapPairs = function(head) { + const dummyHead = new ListNode(); + dummyHead.next = head; + let prev = dummyHead; // 前驱 + let curr = dummyHead.next // 当前 + while(curr != null && curr.next != null) { + const tmp = curr.next.next; + prev.next = curr.next; + curr.next.next = curr; + curr.next = tmp; + + prev = curr; + curr = curr.next; + } + + return dummyHead.next; +}; + +/** + * 24. 两两交换链表中的节点 + * https://leetcode-cn.com/problems/swap-nodes-in-pairs/ + * 递归实现 + * + * @param {ListNode} head + * @return {ListNode} + */ +var swapPairs = function(head) { + if (head === null || head.next === null) { return head; } + const next = head.next; + head.next = swapPairs(next.next); + next.next = head; + + return next; +}; \ No newline at end of file diff --git a/Week_01/id_64/LeetCode_83_64.js b/Week_01/id_64/LeetCode_83_64.js new file mode 100644 index 00000000..cae9d99a --- /dev/null +++ b/Week_01/id_64/LeetCode_83_64.js @@ -0,0 +1,35 @@ +/** + * Definition for singly-linked list. + * function ListNode(val) { + * this.val = val; + * this.next = null; + * } + */ +/** + * 83. 删除排序链表中的重复元素 + * https://leetcode-cn.com/problems/remove-duplicates-from-sorted-list/ + * + * 由于链表是排序的, 只需要遍历链表,并把点前结点的值与后继结点的值比较 + * 如果相等则:current.next = current.next.next + * + * @param {ListNode} head + * @return {ListNode} + */ +var deleteDuplicates = function(head) { + if (head === null) { return head; } + + const dummyHead = new ListNode(); // 使用虚拟头结点 + dummyHead.next = head; + let current = dummyHead; + + while(current.next) { + // 删除结点 + if (current.val === current.next.val) { + current.next = current.next.next; + } else {// 移动结点 + current = current.next; + } + } + + return dummyHead.next; +}; \ No newline at end of file diff --git a/Week_01/id_64/LeetCode_905_64.js b/Week_01/id_64/LeetCode_905_64.js new file mode 100644 index 00000000..de3b1a3a --- /dev/null +++ b/Week_01/id_64/LeetCode_905_64.js @@ -0,0 +1,25 @@ +/** + * 905. 按奇偶排序数组 + * https://leetcode-cn.com/problems/sort-array-by-parity/submissions/ + * 双指针解法,左指针指偶数,右指针指奇数 + * @param {number[]} A + * @return {number[]} + */ +var sortArrayByParity = function(A) { + if (A == null || A.length <= 1) { return A; } + let l = 0; // 偶数左指针 + let r = A.length - 1; // 奇数右指针 + while(l < r) { + // + if (A[l] % 2 == 1 && A[r] % 2 == 0) { + [A[l], A[r]] = [A[r], A[l]]; + } else if (A[l] % 2 == 0) { + l++; // 偶数指针右移 + } else if (A[r] % 2 == 1) { + r--; // 奇数指针左移 + } + + } + + return A; +}; \ No newline at end of file diff --git a/Week_01/id_64/NOTE.md b/Week_01/id_64/NOTE.md index c684e62f..615cbeb2 100644 --- a/Week_01/id_64/NOTE.md +++ b/Week_01/id_64/NOTE.md @@ -1 +1,113 @@ -# 学习笔记 \ No newline at end of file +# 学习笔记 + +## 常用数据结构的小结及 ADT API +- Stack 栈,后进先出(LIFL) + - push(val) + - pop(), remove and return the top element + - peek(), return the last element +- set 集合 + - add(val) + - remove(val) + - has(val) + - values(), return the collection + - size() + - isEmpty() + - union(anotherSet), return union of two sets + - intersection(anotherSet), return intersection of two sets + - difference(anotherSet), return the different of two sets + - subset(subSet), return if subSet is a sub set of current set. +- Queue 队列,先进先出(FIFO)enqueue() -> font->1->2->...->end <- dequeue() + - enquue(val), add + - dequeue(), remove and return the last element + - font(), return the first element + - size() + - isEnpty() +- Binary search tree 二分搜索树 + - add(val), val < node.val -> add to left, val > node.val -> add to right, + - delete(val), left = null, remove right; right = null, remove left; otherwise find mimnNode = minNode(node.rigth), replace node with minNode and remove minNode. + - inOrder() + - preOrder() + - postOrder() + - levelOrder(), push node to a queue, dequeue -> enqueue left node -> enqueue right node, repeat until queue is empty + - isBlance(), minHeight() <= maxHeight - 1 + - minHeight() + - maxHeight() + - minNode() + - maxNode() +- Map 映射, 增删改查都是 O(1) + - collection() + - set(key, val) + - get(key) + - has(key) + - delete(key) + - clear() + - size() +- Hash Table 哈希表 + - add(val) + - remove(val) + - lookup(val) +- Linked list 链表, 增删改查都是 O(n) + - head() + - tail() + - addAt(index, val), O(n) + - getAt(index), O(n) + - remove(val), O(n) + - has(val), O(n) + - isEmpty() +- Trie 字典树, 每个节点都是 map, 根节点为空 + - add(val) + - isWord(val) + - contains(val) + - isPrefix(val) +- Heap 大小堆, 用于优化优先队列, 用数组保存 + - insert(node), 1. add node to the end of the array, 2. siftUp untile parent > node + - findMax(), return the index = 0 of the array + - extratMax(), return the index = 0 and remove it, 1. swap(0, size -1), 2. remove index = size -1, 3. siftDown() + - remove(), remove the root node + - sort(), return a sorted array + - replace(index), replace the root node + - heapify(array), transform an array into a heap, 1. add node to the end of the array, 2. siftDown() + - siftUp(index), sift up a node, make sure parent > left & parent > right + - siftDown(index), sift down a node, make sure parent > left & parent > right + - parent(index), return a node's parent index in the array + - left(index), return a node's left index in the array + - right(index), return a node's right index in the array + +# 书本笔记 +![1](https://user-images.githubusercontent.com/49065208/56456608-2ac5c780-63a1-11e9-9b5b-da7966da2a1b.jpeg) + +![2](https://user-images.githubusercontent.com/49065208/56456609-2ac5c780-63a1-11e9-8876-e529d5b1c58a.jpeg) + +![3](https://user-images.githubusercontent.com/49065208/56456610-2ac5c780-63a1-11e9-8fa7-7bd8397b5f9d.jpeg) + +![4](https://user-images.githubusercontent.com/49065208/56456611-2b5e5e00-63a1-11e9-9ce6-4df39825b3c8.jpeg) + +![5](https://user-images.githubusercontent.com/49065208/56456612-2b5e5e00-63a1-11e9-9d28-7699e32d2f59.jpeg) + +![6](https://user-images.githubusercontent.com/49065208/56456613-2b5e5e00-63a1-11e9-9e84-37c56f230e05.jpeg) + +![7](https://user-images.githubusercontent.com/49065208/56456614-2bf6f480-63a1-11e9-8bae-865eaeecdca3.jpeg) + +![8](https://user-images.githubusercontent.com/49065208/56456615-2bf6f480-63a1-11e9-9cac-2e5c2d51a6f9.jpeg) + +![9](https://user-images.githubusercontent.com/49065208/56456616-2bf6f480-63a1-11e9-88c7-b21411b3972a.jpeg) + +![10](https://user-images.githubusercontent.com/49065208/56456617-2c8f8b00-63a1-11e9-90f8-f9aa8e4a1eb8.jpeg) + +![11](https://user-images.githubusercontent.com/49065208/56456618-2c8f8b00-63a1-11e9-93d1-654ccc441e98.jpeg) + +![12](https://user-images.githubusercontent.com/49065208/56456619-2c8f8b00-63a1-11e9-8203-c1ec7f8f2658.jpeg) + +![13](https://user-images.githubusercontent.com/49065208/56456620-2d282180-63a1-11e9-8bf2-76c6c7881efc.jpeg) + +![14](https://user-images.githubusercontent.com/49065208/56456621-2d282180-63a1-11e9-8963-a9a0973c9871.jpeg) + +![15](https://user-images.githubusercontent.com/49065208/56456622-2d282180-63a1-11e9-8fce-87bc1c45cd7d.jpeg) + +![16](https://user-images.githubusercontent.com/49065208/56456623-2dc0b800-63a1-11e9-82ae-8f0bb87a3b18.jpeg) + +![17](https://user-images.githubusercontent.com/49065208/56456624-2dc0b800-63a1-11e9-96d2-55dff051db5b.jpeg) + +![18](https://user-images.githubusercontent.com/49065208/56456625-2dc0b800-63a1-11e9-8514-9a0e44d06f24.jpeg) + +![19](https://user-images.githubusercontent.com/49065208/56456626-2e594e80-63a1-11e9-8221-6f16f373f14c.jpeg) diff --git a/Week_01/id_65/2222test b/Week_01/id_65/2222test new file mode 100644 index 00000000..f7c6dd01 --- /dev/null +++ b/Week_01/id_65/2222test @@ -0,0 +1 @@ +11111 diff --git a/Week_01/id_65/LeetCode_21_065.java b/Week_01/id_65/LeetCode_21_065.java new file mode 100644 index 00000000..ac03456c --- /dev/null +++ b/Week_01/id_65/LeetCode_21_065.java @@ -0,0 +1,92 @@ +package com.imooc.activiti.helloworld; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +/** + * @author shironghui on 2019/4/18. + */ +class SolutionMerge { + public static ListNode mergeTwoLists(ListNode l1, ListNode l2) { + ListNode newListNode = new ListNode(0); + ListNode cur = newListNode; + while (l1 != null && l2 != null) { + 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 == null) { + cur.next = l2; + } else { + cur.next = l1; + } + return newListNode.next; + } +} +public class TestMerge { + public static int[] stringToIntegerArray(String input) { + input = input.trim(); + input = input.substring(1, input.length() - 1); + if (input.length() == 0) { + return new int[0]; + } + + String[] parts = input.split(","); + int[] output = new int[parts.length]; + for(int index = 0; index < parts.length; index++) { + String part = parts[index].trim(); + output[index] = Integer.parseInt(part); + } + return output; + } + + public static ListNode stringToListNode(String input) { + // Generate array from the input + int[] nodeValues = stringToIntegerArray(input); + + // Now convert that list into linked list + ListNode dummyRoot = new ListNode(0); + ListNode ptr = dummyRoot; + for(int item : nodeValues) { + ptr.next = new ListNode(item); + ptr = ptr.next; + } + return dummyRoot.next; + } + + public static String listNodeToString(ListNode node) { + if (node == null) { + return "[]"; + } + + String result = ""; + while (node != null) { + result += Integer.toString(node.val) + ", "; + node = node.next; + } + return "[" + result.substring(0, result.length() - 2) + "]"; + } + + public static void main(String[] args) throws IOException { + BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); + String line; + while ((line = in.readLine()) != null) { + ListNode l1 = stringToListNode(line); + line = in.readLine(); + ListNode l2 = stringToListNode(line); + + ListNode ret = SolutionMerge.mergeTwoLists(l1, l2); + + String out = listNodeToString(ret); + + System.out.print(out); + } + } +} diff --git a/Week_01/id_65/LeetCode_441_065.java b/Week_01/id_65/LeetCode_441_065.java new file mode 100644 index 00000000..e47b0fb3 --- /dev/null +++ b/Week_01/id_65/LeetCode_441_065.java @@ -0,0 +1,49 @@ +package com.imooc.activiti.helloworld; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +/** + * @author shironghui on 2019/4/18. + */ + + +class Solution14 { + /** + * 让我们按一定规律排列,第一行放1个,第二行放2个,以此类推, + * 问我们有多少行能放满。通过分析题目中的例子可以得知最后一行只有两种情况,放满和没放满。 + * 由于是按等差数列排放的,我们可以快速计算出前i行的硬币总数。 + * 我们先来看一种O(n)的方法,非常简单粗暴,就是从第一行开始,一行一行的从n中减去, + * 如果此时剩余的硬币没法满足下一行需要的硬币数了,我们之间返回当前行数即可 + * @param n + * @return + */ + public int arrangeCoins(int n) { + for(int i=1;i=0){ + n=n-i; + } + else { + return i-2; + } + } + return -1; + } +} + +public class TestArrangeCoins { + public static void main(String[] args) throws IOException { + BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); + String line; + while ((line = in.readLine()) != null) { + int n = Integer.parseInt(line); + + int ret = new Solution14().arrangeCoins(n); + + String out = String.valueOf(ret); + + System.out.print(out); + } + } +} diff --git a/Week_01/id_65/LeetCode_83_065.java b/Week_01/id_65/LeetCode_83_065.java new file mode 100644 index 00000000..5d15637e --- /dev/null +++ b/Week_01/id_65/LeetCode_83_065.java @@ -0,0 +1,88 @@ +package com.imooc.activiti.helloworld; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +/** + * @author shironghui on 2019/4/18. + */ +class Solution { + public static ListNode deleteDuplicates(ListNode head) { + ListNode current=head; + while(current!=null&¤t.next!=null){ + if(current.val==current.next.val){ + current.next=current.next.next; + } + else{ + current=current.next; + } + } + return head; + } +} +public class TestSort { + public static int[] stringToIntegerArray(String input) { + input = input.trim(); + input = input.substring(1, input.length() - 1); + if (input.length() == 0) { + return new int[0]; + } + String[] parts = input.split(","); + int[] output = new int[parts.length]; + for (int index = 0; index < parts.length; index++) { + String part = parts[index].trim(); + output[index] = Integer.parseInt(part); + } + return output; + } + + public static ListNode stringToListNode(String input) { + //generate array from the input + int[] nodeValues = stringToIntegerArray(input); + //Now convert that list into linked list + ListNode dummyRoot = new ListNode(0); + ListNode ptr = dummyRoot; + for (int item : nodeValues) { + ptr.next = new ListNode(item); + ptr = ptr.next; + } + return dummyRoot.next; + } + + public static String listNodeToString(ListNode node) { + if (node == null) { + return "[]"; + } + String result = ""; + while (node != null) { + result += Integer.toString(node.val) + ","; + node = node.next; + } + String substring = result.substring(0, result.length() - 1); + return "[" + substring+ "]"; + } + + public static void main(String[] args) throws IOException { + BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); + String line; + while ((line = in.readLine()) != null) { + ListNode head = stringToListNode(line); + ListNode ret = Solution.deleteDuplicates(head); + String out = listNodeToString(ret); + System.out.println(out); + } + + +// ListNode listNodeOne=new ListNode(1); +// ListNode listNodeTwo=new ListNode(1); +// ListNode listNodeThree=new ListNode(2); +// listNodeOne.next=listNodeTwo; +// listNodeOne.next.next=listNodeThree; +// ListNode listNode = Solution.deleteDuplicates(listNodeOne); +// if(listNode.next==null){ +// +// } +// } + } +} diff --git a/Week_01/id_65/LeetCode_905_065.java b/Week_01/id_65/LeetCode_905_065.java new file mode 100644 index 00000000..67223bc8 --- /dev/null +++ b/Week_01/id_65/LeetCode_905_065.java @@ -0,0 +1,85 @@ +package com.imooc.activiti.helloworld; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +/** + * @author shironghui on 2019/4/18. + */ + + +class Solution3 { + public static int[] sortArrayByParity(int[] A) { + int length=A.length; + int[] B=new int[length]; + int[] C=new int[length]; + int j=0; + int l=0; + for(int i=0;i mappings; + //Initialize hash map with mappings.this simply makes the code easier to read. + public Solution6(){ + this.mappings=new HashMap(); + this.mappings.put(')','('); + this.mappings.put('}','{'); + this.mappings.put(']','['); + } + public boolean isValid(String s){ + Stack stack=new Stack<>(); + for(int i=0;i stack = new Stack<>(); + char[] chars = s.toCharArray(); + for (char aChar : chars) { + if (stack.size() == 0) { + stack.push(aChar); + } else if (isSym(stack.peek(), aChar)) { + stack.pop(); + } else { + stack.push(aChar); + } + } + return stack.size() == 0; + } + + private boolean isSym(char c1, char c2) { + return (c1 == '(' && c2 == ')') + || (c1 == '[' && c2 == ']') + || (c1 == '{' && c2 == '}'); + } +} \ No newline at end of file diff --git a/Week_01/id_67/LeetCode_21_67.java b/Week_01/id_67/LeetCode_21_67.java new file mode 100644 index 00000000..38dbcc52 --- /dev/null +++ b/Week_01/id_67/LeetCode_21_67.java @@ -0,0 +1,36 @@ +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode(int x) { val = x; } + * } + */ +class Solution { + public ListNode mergeTwoLists(ListNode l1, ListNode l2) { + if (l1 == null) return l2; + if (l2 == null) return l1; + + ListNode header = new ListNode(0); + ListNode point = header; + + while (l1 != null && l2 != null) { + if (l1.val <= l2.val) { + point.next = l1; + l1 = l1.next; + } else { + point.next = l2; + l2 = l2.next; + } + point = point.next; + } + if (l1 != null) { + point.next = l1; + } + if (l2 != null) { + point.next = l2; + } + return header.next; + + } +} \ No newline at end of file diff --git a/Week_01/id_67/LeetCode_242_67.java b/Week_01/id_67/LeetCode_242_67.java new file mode 100644 index 00000000..99973511 --- /dev/null +++ b/Week_01/id_67/LeetCode_242_67.java @@ -0,0 +1,18 @@ +class Solution { + public boolean isAnagram(String s, String t) { + int[] x =new int[26]; + + for(char schar: s.toCharArray()){ + x[schar-'a']++; + } + for(char tchar: t.toCharArray()){ + x[tchar-'a']--; + } + for(int i=0;i<26;i++){ + if (x[i] != 0){ + return false; + } + } + return true; + } +} \ No newline at end of file diff --git a/Week_01/id_67/LeetCode_441_67.java b/Week_01/id_67/LeetCode_441_67.java new file mode 100644 index 00000000..21755440 --- /dev/null +++ b/Week_01/id_67/LeetCode_441_67.java @@ -0,0 +1,33 @@ +class Solution { + public int arrangeCoins(int n) { + long start = 0, end = (long) n / 2 + 1, mid; + while (end - start > 1) { + mid = (start + end) >>> 1; + if (mid * (mid + 1) == (long) 2 * n) { + return (int) mid; + } else if (mid * (mid + 1) <= (long) 2 * n) { + start = mid; + } else { + end = mid; + } + } + return (end * (end + 1) == (long) 2 * n) ? (int) end : (int) start; + } + + + public int arrangeCoins2(int n) { + if(n == 0) return 0; + int i=0; + while(n>i){ + + ++i; + n-=i; + } + return i; + } + + public int arrangeCoins3(int n) { + return (int) (Math.sqrt((double) 2*n+0.5)-0.5); + } + +} \ No newline at end of file diff --git a/Week_01/id_67/LeetCode_687_67.java b/Week_01/id_67/LeetCode_687_67.java new file mode 100644 index 00000000..7076f04c --- /dev/null +++ b/Week_01/id_67/LeetCode_687_67.java @@ -0,0 +1,39 @@ +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +class Solution { + int sum; + + public int longestUnivaluePath(TreeNode root) { + sum = 0; + childLength(root); + return sum; + } + + public int childLength(TreeNode node) { + if (node == null) return 0; + int LeftChildLength = childLength(node.left); + int RightChildLength = childLength(node.right); + int LeftLength; + int RightLength; + if(node.left != null && node.left.val == node.val){ + LeftLength = LeftChildLength + 1; + }else { + LeftLength = 0; + } + if(node.right !=null && node.right.val == node.val){ + RightLength = RightChildLength + 1; + }else{ + RightLength = 0; + } + + sum = Math.max(sum, LeftLength + RightLength); + return Math.max(LeftLength, RightLength); + } +} \ No newline at end of file diff --git a/Week_01/id_67/LeetCode_83_67.java b/Week_01/id_67/LeetCode_83_67.java new file mode 100644 index 00000000..dce74444 --- /dev/null +++ b/Week_01/id_67/LeetCode_83_67.java @@ -0,0 +1,23 @@ +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode(int x) { val = x; } + * } + */ +class Solution { + public ListNode deleteDuplicates(ListNode head) { + if (head == null) return head; + ListNode header = new ListNode(0); + header.next = head; + while (head.next != null) { + if (head.val == head.next.val) { + head.next = head.next.next; + }else { + head = head.next; + } + } + return header.next; + } +} \ No newline at end of file diff --git a/Week_01/id_67/LeetCode_905_67.java b/Week_01/id_67/LeetCode_905_67.java new file mode 100644 index 00000000..e08c438b --- /dev/null +++ b/Week_01/id_67/LeetCode_905_67.java @@ -0,0 +1,32 @@ +class Solution { + public int[] sortArrayByParity(int[] A) { + for (int i = 0, j = A.length - 1; i < j; ) { + if (!isOdd(A[i])) { + if (isOdd(A[j])) {//i偶j奇 + ++i; + --j; + } else {//i偶j偶 + ++i; + } + } else { + if (isOdd(A[j])) {//i奇j奇 + --j; + } else {//i奇j偶 + int tmp = A[j]; + A[j] = A[i]; + A[i] = tmp; + } + } + } + return A; + } + + public boolean isOdd(int number) { + if (number % 2 == 0) { + return false; + } else { + return true; + } + } + +} \ No newline at end of file diff --git a/Week_01/id_67/LeetCode_922_67.java b/Week_01/id_67/LeetCode_922_67.java new file mode 100644 index 00000000..37dbc719 --- /dev/null +++ b/Week_01/id_67/LeetCode_922_67.java @@ -0,0 +1,19 @@ +class Solution { + public int[] sortArrayByParityII(int[] A) { + int length = A.length; + int i=0,j=1; + while(i < length){ + if(A[i] % 2 == 0){ + i+=2; + }else { + while(A[j] %2 != 0){ + j+=2; + } + int tmp = A[i]; + A[i] = A[j]; + A[j] = tmp; + } + } + return A; + } +} \ No newline at end of file diff --git a/Week_01/id_69/LeetCode_905_69.java b/Week_01/id_69/LeetCode_905_69.java new file mode 100644 index 00000000..d6161f44 --- /dev/null +++ b/Week_01/id_69/LeetCode_905_69.java @@ -0,0 +1,21 @@ +class Solution { + public int[] sortArrayByParity(int[] A) { + + int length = A.length; + int odd = 0; + int even = length - 1; + int[] tempArray = new int[length]; + + for(int i = 0; i < length; i++){ + if ((A[i] & 1) == 0) { + tempArray[odd] = A[i]; + odd++; + } else { + tempArray[even] = A[i]; + even--; + } + } + + return tempArray; + } +} diff --git a/Week_01/id_69/LeetCode_922_69.java b/Week_01/id_69/LeetCode_922_69.java new file mode 100644 index 00000000..2f2cec2e --- /dev/null +++ b/Week_01/id_69/LeetCode_922_69.java @@ -0,0 +1,20 @@ +class Solution { + public int[] sortArrayByParityII(int[] A) { + int length = A.length; + int j = 0; + int k = 1; + int[] tempArray = new int[A.length]; + + for(int i = 0; i < length; i++){ + if ((A[i] & 1) == 0) { + tempArray[j] = A[i]; + j += 2; + } else { + tempArray[k] = A[i]; + k += 2; + } + } + + return tempArray; + } +} diff --git a/Week_01/id_7/LeetCode_136_7.go b/Week_01/id_7/LeetCode_136_7.go new file mode 100644 index 00000000..7bdaab58 --- /dev/null +++ b/Week_01/id_7/LeetCode_136_7.go @@ -0,0 +1,50 @@ +package geekcode + +/* +https://leetcode-cn.com/problems/single-number/ + +给定一个非空整数数组,除了某个元素只出现一次以外,其余每个元素均出现两次。找出那个只出现了一次的元素。 + +说明: + +你的算法应该具有线性时间复杂度。 你可以不使用额外空间来实现吗? + +示例 1: + +输入: [2,2,1] +输出: 1 +示例 2: + +输入: [4,1,2,1,2] +输出: 4 + + +因为抑或满足交换律,所以, 乱序 也可以随意交换, +把两个相同的放在一起,抑或为 0 , +最后剩下多余的那个数字,就是出现一次的数字 +*/ + +func singleNumber(nums []int) int { + num := 0 + for _, v := range nums { + num = num ^ v + } + return num +} + +/*** +func singleNumber(nums []int) int { + hashnums := make(map[int]int) + for k,v := range nums { + if _,ok := hashnums[v] ; ok { + delete(hashnums,v) + }else { + hashnums[v] = k + } + } + for idx,_ := range(hashnums) { + return idx + } + return -1 +} +**/ diff --git a/Week_01/id_7/LeetCode_1_7.go b/Week_01/id_7/LeetCode_1_7.go new file mode 100644 index 00000000..cd0485a3 --- /dev/null +++ b/Week_01/id_7/LeetCode_1_7.go @@ -0,0 +1,37 @@ +package geekcode + +/* +https://leetcode-cn.com/problems/two-sum/ + +给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。 + +你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。 + +示例: + +给定 nums = [2, 7, 11, 15], target = 9 + +因为 nums[0] + nums[1] = 2 + 7 = 9 +所以返回 [0, 1] + +*/ + +func twoSum(nums []int, target int) []int { + l := len(nums) + hashNums := make(map[int]int) + + // 如果一个数字是解,那么最多出现两次 + for i := 0; i < l; i++ { + hashNums[nums[i]] = i + } + + for i := 0; i < l-1; i++ { + + if idx, ok := hashNums[target-nums[i]]; ok && idx != i { + return []int{i, idx} + } + + } + return nil + +} diff --git a/Week_01/id_7/LeetCode_20_7.go b/Week_01/id_7/LeetCode_20_7.go new file mode 100644 index 00000000..30ca00a5 --- /dev/null +++ b/Week_01/id_7/LeetCode_20_7.go @@ -0,0 +1,132 @@ +package geekcode + +/* +https://leetcode-cn.com/problems/valid-parentheses/ +给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。 + +有效字符串需满足: + +左括号必须用相同类型的右括号闭合。 +左括号必须以正确的顺序闭合。 +注意空字符串可被认为是有效字符串。 + +示例 1: + +输入: "()" +输出: true +示例 2: + +输入: "()[]{}" +输出: true +示例 3: + +输入: "(]" +输出: false +示例 4: + +输入: "([)]" +输出: false +示例 5: + +输入: "{[]}" +输出: true + +*/ + +// 用单链表来实现一个简单的栈, +// push 操作为队尾添加元素 +// pop 操作为从队尾获取元素,前边的元素的next 指向nil +// 判断是否为空 , 判断 last 指向的元素是否为nil +// 考虑到单链表操作,如果从队尾删除数据 即 pop 操作,查找pre 元素,复杂度较高,所以,采用头插法实现链表插入操作 +// 不要担心 last 指针为空,着急改变last 的指向,第一个节点的next 为nil 正好表示栈为空 + +//链表实现的一个栈 +//默认最大元素个数为2048 +type Node struct { + val rune + next *Node +} + +//栈类型 +type Stack struct { + head *Node + size int + max int +} + +//初始化栈,不使用大小参数 +func NewStack() *Stack { + s := new(Stack) + s.size = 0 + s.max = 2048 + return s +} + +// 大小控制,默认可以装2048个元素,可以传递大小参数 +func NewStackWithSize(max int) *Stack { + s := new(Stack) + s.size = 0 + s.max = max + return s +} + +//push 操作注意,头指针的next 指针变动 +//遍历结果,从head 指针往next 遍历即可完成操作 +//超过最大的size ,则入栈失败 +func (self *Stack) Push(c rune) bool { + if self.size >= self.max { + return false + } + self.size++ + self.head = &Node{val: c, next: self.head} + return true +} + +//出栈操作,直接获取头指针,然后改变头指针为头指针的下一个结点 +func (self *Stack) Pop() rune { + if self.head == nil { + return 0 + } + b := self.head.val + self.head = self.head.next + self.size-- + return b +} + +//返回当前栈内的元素个数 +func (self *Stack) Count() int { + return self.size +} + +//检查栈是否为空 +func (self *Stack) IsEmpty() bool { + return self.size == 0 +} + +//检查括号字符串匹配 +func isValid(s string) bool { + stack := NewStack() + var last rune + for _, v := range s { + switch v { + case '(', '[', '{': + stack.Push(v) + case ')': + last = stack.Pop() + if last != '(' { + return false + } + case ']': + last = stack.Pop() + if last != '[' { + return false + } + case '}': + last = stack.Pop() + if last != '{' { + return false + } + } + } + return stack.IsEmpty() +} diff --git a/Week_01/id_7/LeetCode_21_7.go b/Week_01/id_7/LeetCode_21_7.go new file mode 100644 index 00000000..4cdacb2f --- /dev/null +++ b/Week_01/id_7/LeetCode_21_7.go @@ -0,0 +1,133 @@ +package geekcode + +// 题目地址: https://leetcode-cn.com/problems/merge-two-sorted-lists/ +// 合并两个有序链表 +//将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。 +// +//示例: +// +//输入:1->2->4, 1->3->4 +//输出:1->1->2->3->4->4 +// + +import ( + "log" +) + +type ListNode struct { + Val int + Next *ListNode +} + +/** +* 打印list 类型,方便查看list的结果 + */ +func PrintList(list *ListNode) { + l := list + for l != nil { + log.Println(l.Val) + l = l.Next + } +} + +/** +* 初始化列表 +* 使用一个数组初始化 + */ +func InitList(nums []int) *ListNode { + h := new(ListNode) + l := h + for _, v := range nums { + l.Next = &ListNode{Val: v, Next: nil} + l = l.Next + } + return h.Next +} + +/** +* Definition for singly-linked list. +* type ListNode struct { +* Val int +* Next *ListNode +* } +* + 8 ms, 2.8 MB, +*/ +func mergeTwoLists(l1 *ListNode, l2 *ListNode) *ListNode { + + if l1 == nil { + return l2 + } + + if l2 == nil { + return l1 + } + + p0, p1 := l1, l2 + nList := new(ListNode) + p2 := nList + + for p0 != nil || p1 != nil { + switch { + case p0 == nil: + nList.Next = &ListNode{Val: p1.Val, Next: nil} + p1 = p1.Next + case p1 == nil: + nList.Next = &ListNode{Val: p0.Val, Next: nil} + p0 = p0.Next + default: + if p0.Val <= p1.Val { + nList.Next = &ListNode{Val: p0.Val, Next: nil} + p0 = p0.Next + } else { + nList.Next = &ListNode{Val: p1.Val, Next: nil} + p1 = p1.Next + } + } + + nList = nList.Next + } + return p2.Next +} + +/* +* 修改版本,减少内存消耗 +* 4ms , 2.5 MB + */ +func mergeTwoLists2(l1 *ListNode, l2 *ListNode) *ListNode { + + if l1 == nil { + return l2 + } + + if l2 == nil { + return l1 + } + + p0, p1 := l1, l2 + nList := new(ListNode) + p2 := nList + + for p0 != nil || p1 != nil { + switch { + case p0 == nil: + nList.Next = p1 + p1 = p1.Next + case p1 == nil: + nList.Next = p0 + p0 = p0.Next + default: + if p0.Val <= p1.Val { + nList.Next = p0 + p0 = p0.Next + } else { + nList.Next = p1 + p1 = p1.Next + } + } + + nList = nList.Next + } + return p2.Next + +} diff --git a/Week_01/id_7/NOTE.md b/Week_01/id_7/NOTE.md index c684e62f..827330b5 100644 --- a/Week_01/id_7/NOTE.md +++ b/Week_01/id_7/NOTE.md @@ -1 +1,25 @@ -# 学习笔记 \ No newline at end of file +# 学习笔记 + +* 合并两个有序链表: + +[https://leetcode-cn.com/problems/merge-two-sorted-lists/](https://leetcode-cn.com/problems/merge-two-sorted-lists/) + +[merge-two-sorted-lists.go](merge-two-sorted-lists.go) + +* 只出现一次的数字: + +[https://leetcode-cn.com/problems/single-number/](https://leetcode-cn.com/problems/single-number/) + +[single-number.go](single-number.go) + +* 两数之和等于指定数字: + +[https://leetcode-cn.com/problems/two-sum/](https://leetcode-cn.com/problems/two-sum/) + +[two-sum.go](two-sum.go) + +* 合法的括号: + +[https://leetcode-cn.com/problems/valid-parentheses/](https://leetcode-cn.com/problems/valid-parentheses/) + +[valid-parentheses.go](valid-parentheses.go) diff --git a/Week_01/id_7/geek_test.go b/Week_01/id_7/geek_test.go new file mode 100644 index 00000000..efa69293 --- /dev/null +++ b/Week_01/id_7/geek_test.go @@ -0,0 +1,40 @@ +package geekcode + +import ( + "fmt" + "testing" +) + +func NewList(nums []int) { + +} + +func TestMergeList(t *testing.T) { + l1 := InitList([]int{1, 2, 3, 4, 5, 8, 10}) + fmt.Println("print l1") + PrintList(l1) + l2 := InitList([]int{1, 2, 3, 4, 5, 20, 35, 50, 98}) + fmt.Println("print l2") + PrintList(l2) + + //l3 := mergeTwoLists(l1, l2) + l3 := mergeTwoLists2(l1, l2) + PrintList(l3) + +} + +func TestTwoSum(t *testing.T) { + nums := []int{3, 3} + t.Log(twoSum(nums, 6)) +} + +func TestSingleNumber(t *testing.T) { + nums := []int{3, 3, 1} + t.Log(singleNumber(nums)) +} + +func TestValidParenthesses(t *testing.T) { + t.Log("===========") + t.Log(isValid("()")) + t.Log(isValid("(]")) +} diff --git a/Week_01/id_7/readme.md b/Week_01/id_7/readme.md new file mode 100644 index 00000000..eab900c1 --- /dev/null +++ b/Week_01/id_7/readme.md @@ -0,0 +1,25 @@ +# 学习笔记 + +* 合并两个有序链表: + +[https://leetcode-cn.com/problems/merge-two-sorted-lists/](https://leetcode-cn.com/problems/merge-two-sorted-lists/) + +[LeetCode_21_7.go](LeetCode_21_7.go) + +* 只出现一次的数字: + +[https://leetcode-cn.com/problems/single-number/](https://leetcode-cn.com/problems/single-number/) + +[LeetCode_136_7.go](LeetCode_136_7.go) + +* 两数之和等于指定数字: + +[https://leetcode-cn.com/problems/two-sum/](https://leetcode-cn.com/problems/two-sum/) + +[LeetCode_1_7.go](LeetCode_1_7.go) + +* 合法的括号: + +[https://leetcode-cn.com/problems/valid-parentheses/](https://leetcode-cn.com/problems/valid-parentheses/) + +[LeetCode_20_7.go](LeetCode_20_7.go) diff --git a/Week_01/id_71/LeetCode_441_71.js b/Week_01/id_71/LeetCode_441_71.js new file mode 100644 index 00000000..df559bb8 --- /dev/null +++ b/Week_01/id_71/LeetCode_441_71.js @@ -0,0 +1,16 @@ +/** + * @param {number} n + * @return {number} + */ +var arrangeCoins = function (n) { + if (n === 0) { + return 0 + } + let temp = n + for (let i = 1; i <= n; i++) { + temp = temp - i + if (temp === 0 || temp < i + 1) { + return i + } + } +}; \ No newline at end of file diff --git a/Week_01/id_71/LeetCode_687_71.js b/Week_01/id_71/LeetCode_687_71.js new file mode 100644 index 00000000..420c4ab3 --- /dev/null +++ b/Week_01/id_71/LeetCode_687_71.js @@ -0,0 +1,72 @@ +/** + * Definition for a binary tree node. + * function TreeNode(val) { + * this.val = val; + * this.left = this.right = null; + * } + */ +/** + * @param {TreeNode} root + * @return {number} + */ +var longestUnivaluePath = function (root) { + let max = [0] + t(root, max) + return max[0] +}; + +var t = function (root, max) { + + if (!root) { + return 0 + } + + let leftLongestUnivaluePath = t(root.left, max) + let rightLongestUnivaluePath = t(root.right, max) + + if (root.left && root.right && root.left.val === root.val && root.right.val === root.val) { + let currentLongestUnivaluePath = leftLongestUnivaluePath + rightLongestUnivaluePath + 2 + if (max[0] < currentLongestUnivaluePath) { + max[0] = currentLongestUnivaluePath + } + return leftLongestUnivaluePath + 1 > rightLongestUnivaluePath + 1 ? leftLongestUnivaluePath + 1 : rightLongestUnivaluePath + 1 + } + + if (root.left && root.right && root.left.val !== root.val && root.right.val !== root.val) { + let currentLongestUnivaluePath = Math.max(leftLongestUnivaluePath, rightLongestUnivaluePath) + if (max[0] < currentLongestUnivaluePath) { + max[0] = currentLongestUnivaluePath + } + return 0 + } + + if (root.left && root.left.val === root.val) { + leftLongestUnivaluePath += 1 + if (leftLongestUnivaluePath >= rightLongestUnivaluePath) { + if (max[0] < leftLongestUnivaluePath) { + max[0] = leftLongestUnivaluePath + } + } else { + if (max[0] < rightLongestUnivaluePath) { + max[0] = rightLongestUnivaluePath + } + } + return leftLongestUnivaluePath + } + + if (root.right && root.right.val === root.val) { + rightLongestUnivaluePath += 1 + if (rightLongestUnivaluePath >= leftLongestUnivaluePath) { + if (max[0] < rightLongestUnivaluePath) { + max[0] = rightLongestUnivaluePath + } + } else { + if (max[0] < leftLongestUnivaluePath) { + max[0] = leftLongestUnivaluePath + } + } + return rightLongestUnivaluePath + } + + return 0 +} diff --git a/Week_01/id_72/LeetCode_21_72.java b/Week_01/id_72/LeetCode_21_72.java new file mode 100644 index 00000000..99b1af5d --- /dev/null +++ b/Week_01/id_72/LeetCode_21_72.java @@ -0,0 +1,29 @@ +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode(int x) { val = x; } + * } + */ + public ListNode mergeTwoLists(ListNode l1, ListNode l2) { + if (l1 == null && l2 == null) { + return null; + } + if (l1 == null) { + return l2; + } + if (l2 == null) { + return l1; + } + ListNode head = null; + if (l1.val > l2.val) { + head = l2; + head.next = mergeTwoLists(l1, l2.next); + } else { + head = l1; + head.next = mergeTwoLists(l1.next, l2); + } + return head; + } +} \ No newline at end of file diff --git a/Week_01/id_72/LeetCode_687_72.java b/Week_01/id_72/LeetCode_687_72.java new file mode 100644 index 00000000..b0b39447 --- /dev/null +++ b/Week_01/id_72/LeetCode_687_72.java @@ -0,0 +1,44 @@ +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +class Solution { + int maxPath = 0; + + public int longestUnivaluePath(TreeNode root) { + if (root == null) { + return 0; + } + dfs(root); + return maxPath; + } + + private int dfs(TreeNode node) { + if (node == null) { + return 0; + } + int left = dfs(node.left); + if (node.left != null) { + if (node.left.val == node.val) { + left++; + } else { + left = 0; + } + } + int right = dfs(node.right); + if (node.right != null) { + if (node.right.val == node.val) { + right++; + } else { + right = 0; + } + } + maxPath = Math.max(right + left, maxPath); + return Math.max(left, right); + } +} \ No newline at end of file diff --git a/Week_01/id_74/LeetCode_50_74.java b/Week_01/id_74/LeetCode_50_74.java new file mode 100644 index 00000000..627a0c6f --- /dev/null +++ b/Week_01/id_74/LeetCode_50_74.java @@ -0,0 +1,23 @@ +class Solution { + public double myPow(double x, int n) { + if (n < 0) { + return pow(1 / x, -n); + } + return pow(x, n); + } + + public double pow(double x, long n) { + if (n == 0) { + return 1; + } + if (n == 1) { + return x; + } + double result = pow(x, n / 2); + if (n % 2 == 0) { + return result * result; + } else { + return result * result * x; + } + } +} \ No newline at end of file diff --git a/Week_01/id_74/LeetCode_83_74.java b/Week_01/id_74/LeetCode_83_74.java new file mode 100644 index 00000000..f3bf6c41 --- /dev/null +++ b/Week_01/id_74/LeetCode_83_74.java @@ -0,0 +1,22 @@ +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode(int x) { val = x; } + * } + */ +class Solution { + public ListNode deleteDuplicates(ListNode head) { + if (head == null) return null; + ListNode result = head; + while (head.next != null) { + if (head.val == head.next.val) { + head.next = head.next.next; + } else { + head = head.next; + } + } + return result; + } +} \ No newline at end of file diff --git a/Week_01/id_75/LeetCode_21_75.java b/Week_01/id_75/LeetCode_21_75.java new file mode 100644 index 00000000..b6e6729a --- /dev/null +++ b/Week_01/id_75/LeetCode_21_75.java @@ -0,0 +1,33 @@ +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode(int x) { val = x; } + * } + */ +class Solution { + public ListNode mergeTwoLists(ListNode l1, ListNode l2) { + //增加哨兵节点 + ListNode head = new ListNode(0); + ListNode cur = head; + while (l1 != null && l2 != null) { + 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 == null) { + cur.next = l2; + } else { + cur.next = l1; + } + return head.next; + } + +} \ No newline at end of file diff --git a/Week_01/id_75/LeetCode_24_75.java b/Week_01/id_75/LeetCode_24_75.java new file mode 100644 index 00000000..0fa61e88 --- /dev/null +++ b/Week_01/id_75/LeetCode_24_75.java @@ -0,0 +1,17 @@ +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode(int x) { val = x; } + * } + */ +class Solution { + public ListNode swapPairs(ListNode head) { + if(head == null || head.next == null) return head; + ListNode list = head.next; + head.next = swapPairs(list.next); + list.next = head; + return list; + } +} \ No newline at end of file diff --git a/Week_01/id_75/LeetCode_83_75.java b/Week_01/id_75/LeetCode_83_75.java new file mode 100644 index 00000000..726d21c4 --- /dev/null +++ b/Week_01/id_75/LeetCode_83_75.java @@ -0,0 +1,19 @@ +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode(int x) { val = x; } + * } + */ +class Solution { + public ListNode deleteDuplicates(ListNode head) { + if(head == null || head.next == null) return head; + head.next = deleteDuplicates(head.next); + if(head.val != head.next.val){ + return head; + } else { + return head.next; + } + } +} \ No newline at end of file diff --git a/Week_01/id_75/LeetCode_905_75.java b/Week_01/id_75/LeetCode_905_75.java new file mode 100644 index 00000000..4f7dc976 --- /dev/null +++ b/Week_01/id_75/LeetCode_905_75.java @@ -0,0 +1,17 @@ +class Solution { + public int[] sortArrayByParity(int[] A) { + int[] res = new int[A.length]; + //初始化左右指针 + int left = 0,right = A.length - 1; + for(int i = 0; i < A.length; i++){ + if(A[i] % 2 == 0){ + res[left] = A[i]; + left = left + 1; + } else { + res[right] = A[i]; + right = right - 1; + } + } + return res; + } +} \ No newline at end of file diff --git a/Week_01/id_75/LeetCode_922_75.java b/Week_01/id_75/LeetCode_922_75.java new file mode 100644 index 00000000..434835a7 --- /dev/null +++ b/Week_01/id_75/LeetCode_922_75.java @@ -0,0 +1,17 @@ +class Solution { + public int[] sortArrayByParityII(int[] A) { + int oddIndex = 0; + int evenIndex = 1; + int[] res = new int[A.length]; + for(int i = 0;i < A.length; i++){ + if(A[i] % 2 == 0){ + res[oddIndex] = A[i]; + oddIndex = oddIndex + 2; + } else { + res[evenIndex] = A[i]; + evenIndex = evenIndex + 2; + } + } + return res; + } +} \ No newline at end of file diff --git a/Week_01/id_75/NOTE.md b/Week_01/id_75/NOTE.md index c684e62f..02f39a39 100644 --- a/Week_01/id_75/NOTE.md +++ b/Week_01/id_75/NOTE.md @@ -1 +1,14 @@ -# 学习笔记 \ No newline at end of file +# 学习笔记 +本周学习总结 +本周通过刷了几道题,对链表和数组的结构操作掌握比以前更加熟练。在学习过程中应该和做产品一样,由简入难,层层迭代。 + +链表方面: +对链表的指针掌握不够熟练,例如不会熟练使用哨兵节点,指针偶尔指错位置。 +数组方面: +有两道简单题目的空间复杂度有待优化。 +二分查找方面: +取中间值是用mid = low + (high - low)/2还是用mid = (high + low)/2,还是有写错的情况。 + +总结: +在写代码的过程中,把思路以形象的文字图画在纸上表现出来有些吃力,需勤加练习和多向他人借鉴。 +对学习时间整体安排不是十分合理,还有大部分的题目没有用代码实现,例如栈、递归和排序,需要合理安排学习时间。 diff --git a/Week_01/id_76/LeetCode_20_6.C++ b/Week_01/id_76/LeetCode_20_6.C++ new file mode 100644 index 00000000..7674bda0 --- /dev/null +++ b/Week_01/id_76/LeetCode_20_6.C++ @@ -0,0 +1,103 @@ +#include "stdafx.h" +#include +#include +using namespace std; + + +//https://leetcode-cn.com/problems/remove-duplicates-from-sorted-list/ +//Author : λ +//Date : 2019-04-15 + +/* +Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. + + An input string is valid if: + +Open brackets must be closed by the same type of brackets. + Open brackets must be closed in the correct order. + Note that an empty string is also considered valid. + + Example 1: + +Input: "()" +Output: true + Example 2: + +Input: "()[]{}" +Output: true + Example 3: + +Input: "(]" +Output: false + Example 4: + +Input: "([)]" +Output: false + Example 5: + +Input: "{[]}" +Output: true +*/ + +// ˼·Կջ'(','[','{'ջɣ']'')''}'ʱջԪǷţǾͳջջ +// ʱ临ӶO(n),ռ临ӶO(n) + +class Solution { +public: + bool isValid(string s) { + + std::stack ret; + int len = s.length(); + for (int i = 0; i < len; i++) + { + char sz = s[i]; + switch (sz) + { + case '(': + ret.push(sz); + break; + case '[': + ret.push(sz); + break; + case '{': + ret.push(sz); + break; + case ')': + { + if (ret.top() == '(') + ret.pop(); + else + ret.push(sz); + } + break; + case ']': + { + if (ret.top() == '[') + ret.pop(); + else + ret.push(sz); + } + break; + case '}': + { + if (ret.top() == '{') + ret.pop(); + else + ret.push(sz); + } + break; + default: + break; + } + } + return ret.empty(); + } +}; + + +int _tmain(int argc, _TCHAR* argv[]){ + + Solution sln; + sln.isValid("(("); + return 0; +} \ No newline at end of file diff --git a/Week_01/id_76/LeetCode_83_6.C++ b/Week_01/id_76/LeetCode_83_6.C++ new file mode 100644 index 00000000..f272052e --- /dev/null +++ b/Week_01/id_76/LeetCode_83_6.C++ @@ -0,0 +1,62 @@ +#include "stdafx.h" + +//https://leetcode-cn.com/problems/remove-duplicates-from-sorted-list/ +//Author : λ +//Date : 2019-04-15 + + +/* +Given a sorted linked list, delete all duplicates such that each element appear only once. + + Example 1: + +Input: 1->1->2 +Output: 1->2 + Example 2: + +Input: 1->1->2->3->3 +Output: 1->2->3 +*/ + + // Definition for singly-linked list. + struct ListNode { + int val; + ListNode *next; + ListNode(int x) : val(x), next(NULL) {} + }; + +// ˼·һǴСͬСֻᰤһ +// curָ룬curֵǷcur->nextֵھɾcur->nextڵ㣬ѭȣͰcur->nextָ븳ֵcur +// ߽headΪգҲֻһڵ +// ʱ临ӶO(n)ռ临ӶO(1) +class Solution { +public: + ListNode* deleteDuplicates(ListNode* head) { + ListNode *cur = head; + if (cur == NULL){ + return cur; + } + + if (cur->next == NULL){ + return cur; + } + + while (cur != NULL && cur->next != NULL){ + if (cur->val == cur->next->val){ + cur->next = cur->next->next; + } + else{ + cur = cur->next; + } + } + return head; + } +}; + + +int _tmain(int argc, _TCHAR* argv[]){ + + Solution sln; + sln.deleteDuplicates(NULL); + return 0; +} \ No newline at end of file diff --git a/Week_01/id_76/LeetCode_88_6.C++ b/Week_01/id_76/LeetCode_88_6.C++ new file mode 100644 index 00000000..8a328f66 --- /dev/null +++ b/Week_01/id_76/LeetCode_88_6.C++ @@ -0,0 +1,48 @@ +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode(int x) : val(x), next(NULL) {} + * }; + */ +class Solution { +public: + ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { + + ListNode* p1 = l1; + ListNode* p2 = l2; + + ListNode* L = (ListNode*)malloc(sizeof(ListNode)); + ListNode* r = L; + while (p1 != NULL && p2 != NULL) + { + if (p1->val <= p2->val) + { + r->next = p1; + p1 = p1->next; + } + else + { + r->next = p2; + p2 = p2->next; + } + + r = r->next; + } + + if (p1 != NULL) + { + r->next = p1; + } + + if (p2 != NULL) + { + r->next = p2; + } + + ListNode* p = L->next; + free(L); + return p; + } +}; \ No newline at end of file diff --git a/Week_01/id_77/leet_code.md b/Week_01/id_77/leet_code.md new file mode 100644 index 00000000..5b66b7de --- /dev/null +++ b/Week_01/id_77/leet_code.md @@ -0,0 +1,804 @@ +### 链表 + +#### [83. 删除排序链表中的重复元素](https://leetcode-cn.com/problems/remove-duplicates-from-sorted-list/) + +给定一个排序链表,删除所有重复的元素,使得每个元素只出现一次。 + +**示例 1:** + +``` +输入: 1->1->2 +输出: 1->2 +``` + +**示例 2:** + +``` +输入: 1->1->2->3->3 +输出: 1->2->3 +``` + +**代码:** + +```java +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode(int x) { val = x; } + * } + */ +class Solution { + public ListNode deleteDuplicates(ListNode head) { + ListNode pointer = head; + + while(pointer!=null){ + if(pointer.next!=null && pointer.val== pointer.next.val){ + pointer.next = pointer.next.next; + }else{ + pointer = pointer.next; + } + + } + return head; + } +} +``` + +#### [21. 合并两个有序链表](https://leetcode-cn.com/problems/merge-two-sorted-lists/) + +将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。 + +**示例:** + +``` +输入:1->2->4, 1->3->4 +输出:1->1->2->3->4->4 +``` + +**代码:** + +```java +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode(int x) { val = x; } + * } + */ +class Solution { + public ListNode mergeTwoLists(ListNode l1, ListNode l2) { + ListNode p1 = l1; + ListNode p2 = l2; + + if(l1==null){ + return l2; + }else if(l2==null){ + return l1; + } + ListNode listNew ; + if(p1.val2->3->4, 你应该返回 2->1->4->3. +``` + +**代码:** + +```java +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode(int x) { val = x; } + * } + */ +class Solution { + public ListNode swapPairs(ListNode head) { + if(head == null || head.next == null){ + return head; + } + ListNode slowPointer = head; + ListNode fastPointer = head.next; + ListNode p=fastPointer.next; + + fastPointer.next = slowPointer; + slowPointer.next =p; + + if(p == null){ + return fastPointer; + } + head = fastPointer; + ListNode headPointer = fastPointer.next; + + slowPointer = p; + fastPointer = p.next; + + while(slowPointer != null && fastPointer !=null){ + p=fastPointer.next; + fastPointer.next = slowPointer; + slowPointer.next =p; + headPointer.next = fastPointer; + headPointer = fastPointer.next; + slowPointer = p; + if(p!=null){ + fastPointer = p.next; + }else{ + fastPointer= null; + } + } + return head; + } +} +``` + +#### [142. 环形链表 II](https://leetcode-cn.com/problems/linked-list-cycle-ii/) + +给定一个链表,返回链表开始入环的第一个节点。 如果链表无环,则返回 `null`。 + +为了表示给定链表中的环,我们使用整数 `pos` 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 `pos` 是 `-1`,则在该链表中没有环。 + +**说明:**不允许修改给定的链表。 + + + +**示例 1:** + +``` +输入:head = [3,2,0,-4], pos = 1 +输出:tail connects to node index 1 +解释:链表中有一个环,其尾部连接到第二个节点。 +``` + +![img](https://assets.leetcode-cn.com/aliyun-lc-upload/uploads/2018/12/07/circularlinkedlist.png) + +**示例 2:** + +``` +输入:head = [1,2], pos = 0 +输出:tail connects to node index 0 +解释:链表中有一个环,其尾部连接到第一个节点。 +``` + +![img](https://assets.leetcode-cn.com/aliyun-lc-upload/uploads/2018/12/07/circularlinkedlist_test2.png) + +**示例 3:** + +``` +输入:head = [1], pos = -1 +输出:no cycle +解释:链表中没有环。 +``` + +![img](https://assets.leetcode-cn.com/aliyun-lc-upload/uploads/2018/12/07/circularlinkedlist_test3.png) + +**代码:** + +```java +/** + * Definition for singly-linked list. + * class ListNode { + * int val; + * ListNode next; + * ListNode(int x) { + * val = x; + * next = null; + * } + * } + */ +public class Solution { + public ListNode detectCycle(ListNode head) { + Set cache = new HashSet(); + + while(head != null){ + if(cache.contains(head)){ + return head; + }else{ + cache.add(head); + head = head.next; + } + } + + return null; + + } +} +``` + +#### 25.k个一组翻转链表 + +给出一个链表,每 *k* 个节点一组进行翻转,并返回翻转后的链表。 + +*k* 是一个正整数,它的值小于或等于链表的长度。如果节点总数不是 *k* 的整数倍,那么将最后剩余节点保持原有顺序。 + +**示例 :** + +给定这个链表:`1->2->3->4->5` + +当 *k* = 2 时,应当返回: `2->1->4->3->5` + +当 *k* = 3 时,应当返回: `3->2->1->4->5` + +**说明 :** + +- 你的算法只能使用常数的额外空间。 +- **你不能只是单纯的改变节点内部的值**,而是需要实际的进行节点交换。 + +**代码:** + +```java +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode(int x) { val = x; } + * } + */ +class Solution { + public ListNode reverseKGroup(ListNode head, int k) { + + if(head == null){ + return null; + } + + //记录头节点 + ListNode headPointer = head; + //记录尾节点 + ListNode tailPointer = head; + //记录节点个数 + int n = 0; + while(tailPointer != null){ + n++; + if(n == k){ + //k以后的节点递归处理 + ListNode tmpTail = reverseKGroup(tailPointer.next,k); + //反转前k个节点 并链接尾节点 + reverseK(headPointer,k).next = tmpTail; + break; + } + tailPointer = tailPointer.next; + } + + if(n < k){ + //不足k个节点 直接返回头节点 + return headPointer; + }else{ + //有k个节点 返回反转后的头节点 即原来的尾节点 + return tailPointer; + } + + + } + + public ListNode reverseK(ListNode head, int k){ + if(k == 1){ + return head; + } + ListNode headNew = reverseK(head.next,k-1); + headNew.next = head; + head.next = null; + + return head; + } + + +} +``` + +### 数组 + +#### [905. 按奇偶排序数组](https://leetcode-cn.com/problems/sort-array-by-parity/) + +给定一个非负整数数组 `A`,返回一个由 `A` 的所有偶数元素组成的数组,后面跟 `A` 的所有奇数元素。 + +你可以返回满足此条件的任何数组作为答案。 + + + +**示例:** + +``` +输入:[3,1,2,4] +输出:[2,4,3,1] +输出 [4,2,3,1],[2,4,1,3] 和 [4,2,1,3] 也会被接受。 +``` + + + +**提示:** + +1. `1 <= A.length <= 5000` +2. `0 <= A[i] <= 5000` + +```java +class Solution { + + + public int[] sortArrayByParity(int[] A) { + int[] arr =new int[A.length]; + int start = -1, end = A.length; + for(int i=0;i -1; + }else if(nums[0] == target){ + return true; + }else{ + while(left < end && nums[left] == nums[left+1]){ + left++; + } + while(right > 0 && nums[right] == nums[right-1]){ + right--; + } + } + + int maxIndex = -1; + + while(left <= right){ + mid = left + ((right - left) >> 1); + if(nums[mid] > nums[mid+1]){ + maxIndex = mid; + break; + }else if(nums[mid] < nums[0]){ + right = mid -1; + }else{ + left = mid +1; + } + } + if(target < nums[0]){ + return binarySearch(nums,target,maxIndex+1 ,end) > -1; + }else{ + return binarySearch(nums,target,0 ,maxIndex) > -1; + } + + } + + public int binarySearch(int[] nums,int target,int left ,int right){ + if(left>right){ + return -1; + } + int mid = left + ((right - left) >> 1); + if(nums[mid] > target){ + return binarySearch(nums,target,left,mid-1); + }else if(nums[mid] < target){ + return binarySearch(nums,target,mid + 1,right); + }else{ + return mid; + } + } +} +``` + +#### [153. 寻找旋转排序数组中的最小值](https://leetcode-cn.com/problems/find-minimum-in-rotated-sorted-array/) + +假设按照升序排序的数组在预先未知的某个点上进行了旋转。 + +( 例如,数组 `[0,1,2,4,5,6,7]` 可能变为 `[4,5,6,7,0,1,2]` )。 + +请找出其中最小的元素。 + +你可以假设数组中不存在重复元素。 + +**示例 1:** + +``` +输入: [3,4,5,1,2] +输出: 1 +``` + +**示例 2:** + +``` +输入: [4,5,6,7,0,1,2] +输出: 0 +``` + +**代码:** + +```java +class Solution { + public int findMin(int[] nums) { + int left = 0,right = nums.length-1,end = nums.length-1,mid; + if(end < 0){ + return -1; + }else if(end == 0){ + return nums[0]; + } + + if(nums[0]> 1); + if(nums[mid] > nums[mid+1]){ + maxIndex = mid; + break; + }else if(nums[mid] < nums[0]){ + right = mid -1; + }else{ + left = mid +1; + } + } + return nums[maxIndex + 1]; + } +} +``` + +#### [33. 搜索旋转排序数组](https://leetcode-cn.com/problems/search-in-rotated-sorted-array/) + +假设按照升序排序的数组在预先未知的某个点上进行了旋转。 + +( 例如,数组 `[0,1,2,4,5,6,7]` 可能变为 `[4,5,6,7,0,1,2]` )。 + +搜索一个给定的目标值,如果数组中存在这个目标值,则返回它的索引,否则返回 `-1` 。 + +你可以假设数组中不存在重复的元素。 + +你的算法时间复杂度必须是 *O*(log *n*) 级别。 + +**示例 1:** + +``` +输入: nums = [4,5,6,7,0,1,2], target = 0 +输出: 4 +``` + +**示例 2:** + +``` +输入: nums = [4,5,6,7,0,1,2], target = 3 +输出: -1 +``` + +**代码:** + +```java +class Solution { + + public int search(int[] nums, int target) { + int left = 0,right = nums.length-1,end = nums.length-1,mid; + if(end < 0){ + return -1; + }else if(end == 0){ + return nums[0] == target ? 0 : -1; + } + + if(nums[0]> 1); + if(nums[mid] > nums[mid+1]){ + maxIndex = mid; + break; + }else if(nums[mid] < nums[0]){ + right = mid -1; + }else{ + left = mid +1; + } + } + + //比较最大值 进行区间二分查找 + if(target < nums[0]){ + return binarySearch(nums,target,maxIndex+1 ,end) ; + }else{ + return binarySearch(nums,target,0 ,maxIndex) ; + } + +} + +public int binarySearch(int[] nums,int target,int left ,int right){ + if(left>right){ + return -1; + } + int mid = left + ((right - left) >> 1); + if(nums[mid] > target){ + return binarySearch(nums,target,left,mid-1); + }else if(nums[mid] < target){ + return binarySearch(nums,target,mid + 1,right); + }else{ + return mid; + } +} +} +``` + +### 栈 + +#### [20. 有效的括号](https://leetcode-cn.com/problems/valid-parentheses/) + +```java +给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。 + +有效字符串需满足: + +左括号必须用相同类型的右括号闭合。 +左括号必须以正确的顺序闭合。 +注意空字符串可被认为是有效字符串。 + +示例 1: + +输入: "()" +输出: true +示例 2: + +输入: "()[]{}" +输出: true +示例 3: + +输入: "(]" +输出: false +示例 4: + +输入: "([)]" +输出: false +示例 5: + +输入: "{[]}" +输出: true +``` + +**代码:** + +```java +class Solution { + public boolean isValid(String s) { + Stack stack = new Stack(); + if(s.length() == 0){ + return true; + } + boolean flag = true; + char ch; + for(int i=0;i0){ + return false; + }else { + return flag; + } + } +} +``` + +#### [496. 下一个更大元素 I](https://leetcode-cn.com/problems/next-greater-element-i/) + +给定两个**没有重复元素**的数组 `nums1` 和 `nums2` ,其中`nums1` 是 `nums2` 的子集。找到 `nums1` 中每个元素在 `nums2` 中的下一个比其大的值。 + +`nums1` 中数字 **x** 的下一个更大元素是指 **x** 在 `nums2` 中对应位置的右边的第一个比 **x** 大的元素。如果不存在,对应位置输出-1。 + +**示例 1:** + +``` +输入: nums1 = [4,1,2], nums2 = [1,3,4,2]. +输出: [-1,3,-1] +解释: + 对于num1中的数字4,你无法在第二个数组中找到下一个更大的数字,因此输出 -1。 + 对于num1中的数字1,第二个数组中数字1右边的下一个较大数字是 3。 + 对于num1中的数字2,第二个数组中没有下一个更大的数字,因此输出 -1。 +``` + +**示例 2:** + +``` +输入: nums1 = [2,4], nums2 = [1,2,3,4]. +输出: [3,-1] +解释: + 对于num1中的数字2,第二个数组中的下一个较大数字是3。 + 对于num1中的数字4,第二个数组中没有下一个更大的数字,因此输出 -1。 +``` + +**注意:** + +1. `nums1`和`nums2`中所有元素是唯一的。 +2. `nums1`和`nums2` 的数组大小都不超过1000。 + +**代码:** + +```java +class Solution { + // 默认初始值 + private static final Integer VALUED_EFAULT = Integer.valueOf(-1); + + public int[] nextGreaterElement(int[] nums1, int[] nums2) { + + Stack stack = new Stack(); + //利用哨兵来去除判空 + stack.push(Integer.MAX_VALUE); + Map map = new HashMap(); + int[] arr = new int[nums1.length]; + for(Integer node:nums2){ + while( node > stack.peek()){ + map.put(stack.pop(),node); + } + stack.push(node); + } + + for(int i = 0;i < nums1.length;i++){ + //获取为空时添加默认值 + arr[i] = map.getOrDefault(nums1[i],VALUED_EFAULT); + } + return arr; + + } +} +``` + diff --git a/Week_01/id_77/leetcode_153_077.java b/Week_01/id_77/leetcode_153_077.java new file mode 100644 index 00000000..ad770ea9 --- /dev/null +++ b/Week_01/id_77/leetcode_153_077.java @@ -0,0 +1,29 @@ +class Solution { + public int findMin(int[] nums) { + int left = 0,right = nums.length-1,end = nums.length-1,mid; + if(end < 0){ + return -1; + }else if(end == 0){ + return nums[0]; + } + + if(nums[0]> 1); + if(nums[mid] > nums[mid+1]){ + maxIndex = mid; + break; + }else if(nums[mid] < nums[0]){ + right = mid -1; + }else{ + left = mid +1; + } + } + return nums[maxIndex + 1]; + } +} \ No newline at end of file diff --git a/Week_01/id_77/leetcode_20_077.java b/Week_01/id_77/leetcode_20_077.java new file mode 100644 index 00000000..442cfb66 --- /dev/null +++ b/Week_01/id_77/leetcode_20_077.java @@ -0,0 +1,45 @@ +class Solution { + public boolean isValid(String s) { + Stack stack = new Stack(); + if(s.length() == 0){ + return true; + } + boolean flag = true; + char ch; + for(int i=0;i0){ + return false; + }else { + return flag; + } + } +} \ No newline at end of file diff --git a/Week_01/id_77/leetcode_21_077.java b/Week_01/id_77/leetcode_21_077.java new file mode 100644 index 00000000..fd74782b --- /dev/null +++ b/Week_01/id_77/leetcode_21_077.java @@ -0,0 +1,51 @@ +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode(int x) { val = x; } + * } + */ +class Solution { + public ListNode mergeTwoLists(ListNode l1, ListNode l2) { + ListNode p1 = l1; + ListNode p2 = l2; + + if(l1==null){ + return l2; + }else if(l2==null){ + return l1; + } + ListNode listNew ; + if(p1.val> 1); + if(nums[mid] > nums[mid+1]){ + maxIndex = mid; + break; + }else if(nums[mid] < nums[0]){ + right = mid -1; + }else{ + left = mid +1; + } + } + + //比较最大值 进行区间二分查找 + if(target < nums[0]){ + return binarySearch(nums,target,maxIndex+1 ,end) ; + }else{ + return binarySearch(nums,target,0 ,maxIndex) ; + } + +} + +public int binarySearch(int[] nums,int target,int left ,int right){ + if(left>right){ + return -1; + } + int mid = left + ((right - left) >> 1); + if(nums[mid] > target){ + return binarySearch(nums,target,left,mid-1); + }else if(nums[mid] < target){ + return binarySearch(nums,target,mid + 1,right); + }else{ + return mid; + } +} +} \ No newline at end of file diff --git a/Week_01/id_77/leetcode_33_077.java b/Week_01/id_77/leetcode_33_077.java new file mode 100644 index 00000000..c85c8c4e --- /dev/null +++ b/Week_01/id_77/leetcode_33_077.java @@ -0,0 +1,51 @@ +class Solution { + + public int search(int[] nums, int target) { + int left = 0,right = nums.length-1,end = nums.length-1,mid; + if(end < 0){ + return -1; + }else if(end == 0){ + return nums[0] == target ? 0 : -1; + } + + if(nums[0]> 1); + if(nums[mid] > nums[mid+1]){ + maxIndex = mid; + break; + }else if(nums[mid] < nums[0]){ + right = mid -1; + }else{ + left = mid +1; + } + } + + //比较最大值 进行区间二分查找 + if(target < nums[0]){ + return binarySearch(nums,target,maxIndex+1 ,end) ; + }else{ + return binarySearch(nums,target,0 ,maxIndex) ; + } + +} + +public int binarySearch(int[] nums,int target,int left ,int right){ + if(left>right){ + return -1; + } + int mid = left + ((right - left) >> 1); + if(nums[mid] > target){ + return binarySearch(nums,target,left,mid-1); + }else if(nums[mid] < target){ + return binarySearch(nums,target,mid + 1,right); + }else{ + return mid; + } +} +} \ No newline at end of file diff --git a/Week_01/id_77/leetcode_496_077.java b/Week_01/id_77/leetcode_496_077.java new file mode 100644 index 00000000..1f3ba616 --- /dev/null +++ b/Week_01/id_77/leetcode_496_077.java @@ -0,0 +1,26 @@ +class Solution { + // 默认初始值 + private static final Integer VALUED_EFAULT = Integer.valueOf(-1); + + public int[] nextGreaterElement(int[] nums1, int[] nums2) { + + Stack stack = new Stack(); + //利用哨兵来去除判空 + stack.push(Integer.MAX_VALUE); + Map map = new HashMap(); + int[] arr = new int[nums1.length]; + for(Integer node:nums2){ + while( node > stack.peek()){ + map.put(stack.pop(),node); + } + stack.push(node); + } + + for(int i = 0;i < nums1.length;i++){ + //获取为空时添加默认值 + arr[i] = map.getOrDefault(nums1[i],VALUED_EFAULT); + } + return arr; + + } +} \ No newline at end of file diff --git a/Week_01/id_77/leetcode_81_077.java b/Week_01/id_77/leetcode_81_077.java new file mode 100644 index 00000000..e8d2e5b3 --- /dev/null +++ b/Week_01/id_77/leetcode_81_077.java @@ -0,0 +1,57 @@ +class Solution { + public boolean search(int[] nums, int target) { + int left = 0,right = nums.length-1,end = nums.length-1,mid; + if(end < 0){ + return false; + }else if(end == 0){ + return nums[0] == target; + } + + if(nums[0] -1; + }else if(nums[0] == target){ + return true; + }else{ + while(left < end && nums[left] == nums[left+1]){ + left++; + } + while(right > 0 && nums[right] == nums[right-1]){ + right--; + } + } + + int maxIndex = -1; + + while(left <= right){ + mid = left + ((right - left) >> 1); + if(nums[mid] > nums[mid+1]){ + maxIndex = mid; + break; + }else if(nums[mid] < nums[0]){ + right = mid -1; + }else{ + left = mid +1; + } + } + if(target < nums[0]){ + return binarySearch(nums,target,maxIndex+1 ,end) > -1; + }else{ + return binarySearch(nums,target,0 ,maxIndex) > -1; + } + + } + + public int binarySearch(int[] nums,int target,int left ,int right){ + if(left>right){ + return -1; + } + int mid = left + ((right - left) >> 1); + if(nums[mid] > target){ + return binarySearch(nums,target,left,mid-1); + }else if(nums[mid] < target){ + return binarySearch(nums,target,mid + 1,right); + }else{ + return mid; + } + } +} \ No newline at end of file diff --git a/Week_01/id_77/leetcode_83_077.java b/Week_01/id_77/leetcode_83_077.java new file mode 100644 index 00000000..308f163c --- /dev/null +++ b/Week_01/id_77/leetcode_83_077.java @@ -0,0 +1,23 @@ +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode(int x) { val = x; } + * } + */ +class Solution { + public ListNode deleteDuplicates(ListNode head) { + ListNode pointer = head; + + while(pointer!=null){ + if(pointer.next!=null && pointer.val== pointer.next.val){ + pointer.next = pointer.next.next; + }else{ + pointer = pointer.next; + } + + } + return head; + } +} \ No newline at end of file diff --git a/Week_01/id_77/leetcode_905_077.java b/Week_01/id_77/leetcode_905_077.java new file mode 100644 index 00000000..b3e0c9b4 --- /dev/null +++ b/Week_01/id_77/leetcode_905_077.java @@ -0,0 +1,20 @@ +class Solution { + + + public int[] sortArrayByParity(int[] A) { + int[] arr =new int[A.length]; + int start = -1, end = A.length; + for(int i=0;i2->3->4, 你应该返回 2->1->4->3. + +*/ + +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * struct ListNode *next; + * }; + */ + +struct ListNode* swapPairs(struct ListNode* head) { + + if (head == NULL || head->next == NULL) { + return head; + } + + struct ListNode *curr = head; + struct ListNode *next = NULL; + struct ListNode *a = NULL; + struct ListNode *b = NULL; + + struct ListNode node; + node.val = -1; + node.next = NULL; + struct ListNode *prev = &node; + + while (curr && curr->next) { + a = curr; + b = curr->next; + next = b->next; + b->next = a; + a->next = next; + + prev->next = b; + prev = curr; + curr = next; + } + + return node.next; +} + diff --git a/Week_01/id_78/LeetCode_50_78.c b/Week_01/id_78/LeetCode_50_78.c new file mode 100644 index 00000000..f06ca0eb --- /dev/null +++ b/Week_01/id_78/LeetCode_50_78.c @@ -0,0 +1,43 @@ +/* +实现 pow(x, n) ,即计算 x 的 n 次幂函数。 + +示例 1: + +输入: 2.00000, 10 +输出: 1024.00000 +示例 2: + +输入: 2.10000, 3 +输出: 9.26100 +示例 3: + +输入: 2.00000, -2 +输出: 0.25000 +解释: 2-2 = 1/22 = 1/4 = 0.25 +说明: + +-100.0 < x < 100.0 +n 是 32 位有符号整数,其数值范围是 [−231, 231 − 1] 。 +*/ + +double myPow(double x, int n) { + double pow = 1; + + if (n < 0) { + x = 1/x; + n = -n; + } + + while (n > 0) { + + if (n % 2 == 1) { + pow = pow * x; + } + + x = x * x; + n = n >> 1; + } + + return pow; +} + diff --git a/Week_01/id_81/LeetCode_20_81.java b/Week_01/id_81/LeetCode_20_81.java new file mode 100644 index 00000000..9a3d619d --- /dev/null +++ b/Week_01/id_81/LeetCode_20_81.java @@ -0,0 +1,39 @@ +/** + * @author apple + */ + +public class IsValidByStack { + + /** + * 利用栈的特性,注意各种边界条件与判空条件 + * + * @param s + * @return + */ + public static boolean isValid(String s) { + if (s.equals("") || s == null) + return true; + if (s.length() % 2 == 1) + return false; + Stack stack = new Stack<>(); + for (int i = 0; i < s.length(); ++i) { + char temp = s.charAt(i); + if (temp == '(' || temp == '{' || temp == '[') + stack.push(temp); + else { + if (!stack.isEmpty()) { + if (temp == ')' && stack.pop() != '(') { + return false; + } + if (temp == ']' && stack.pop() != '[') { + return false; + } + if (temp == '}' && stack.pop() != '{') { + return false; + } + } + } + } + return stack.isEmpty(); + } +} diff --git a/Week_01/id_81/LeetCode_21_81.java b/Week_01/id_81/LeetCode_21_81.java new file mode 100644 index 00000000..1e0968c7 --- /dev/null +++ b/Week_01/id_81/LeetCode_21_81.java @@ -0,0 +1,56 @@ +/* + * https://leetcode-cn.com/problems/merge-two-sorted-lists/ + * + * @author apple + * @desc 将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。 + * 示例: 输入:1->2->4, 1->3->4 + * 输出:1->1->2->3->4->4 + */ +public class MergeTwoListNode { + + // @desc 刚开始是有两种思路吧: 1. 将其中一个链表的数据插入到另一个列表之中 2. 重新定义一个链表将其加入。 + // 我使用的是第二种方式 + // 注意点:在编写代码的时候遇到了很多坑吧,应该就是自己平时练的太少,很多地方刚开始都没有想到。 + // 1. 要定义两个节点,一个节点用来保存合并生成的 头结点 head,一个节点负责去合并两个链表;我一开始只定义了一个节点 + // 2. head = new ListNode(l1.val); 这里赋值时,我最开始 是这样赋值的 head = + // list,这里傻了,忘了链表的指针了,导致后边赋值时,直接把好多的值都覆盖掉了 + // 3. 还有一个问题就是,赋值后一定要记得 continue + + public static ListNode mergeTwoLists(ListNode l1, ListNode l2) { + if (l1 == null) + return l2; + if (l2 == null) + return l1; + ListNode head = null; + ListNode pre = null; + while (l1 != null && l2 != null) { + if (l1.val <= l2.val) { + if (pre == null) { + head = new ListNode(l1.val); + pre = head; + } else { + pre.next = new ListNode(l1.val); + pre = pre.next; + } + l1 = l1.next; + continue; + } + if (l2.val < l1.val) { + if (pre == null) { + head = new ListNode(l2.val); + pre = head; + } else { + pre.next = new ListNode(l2.val); + pre = pre.next; + } + l2 = l2.next; + continue; + } + } + if (l1 == null) + pre.next = l2; + if (l2 == null) + pre.next = l1; + return head; + } +} diff --git a/Week_01/id_81/LeetCode_242_81.java b/Week_01/id_81/LeetCode_242_81.java new file mode 100644 index 00000000..b764a021 --- /dev/null +++ b/Week_01/id_81/LeetCode_242_81.java @@ -0,0 +1,16 @@ +/** + * @author okbeng + * @desc 首先将字符串转换成 char 数组,然后对其进行排序,最后在用 Arrays 工 * 具类判断其是否相同。注意限类判断条件。 + * @date 2019-04-18 22:49 + */ +class Solution { + public boolean isAnagram(String s, String t) { + if(s.length() != t.length()) + return false; + char[] arr1 = s.toCharArray(); + Arrays.sort(arr1); + char[] arr2 = t.toCharArray(); + Arrays.sort(arr2); + return Arrays.equals(arr1, arr2); + } +} diff --git a/Week_01/id_81/LeetCode_441_81.java b/Week_01/id_81/LeetCode_441_81.java new file mode 100644 index 00000000..9d966afd --- /dev/null +++ b/Week_01/id_81/LeetCode_441_81.java @@ -0,0 +1,29 @@ +/** + * 思路: + * 例图: n=5 + * * + * ** + * ** + * 从图中可以看出,本题中如果是正常的梯形,第一行 1 *,第二行 2 ** ,第三行 3 *** .. + * 因此使用 index 来标记行,每排列一行,n 就要减去对应的行数, + * 也就是 第一行 index = 1, 排列之后, n 还剩 n=n-index=4, 第二行 index = 2,排列之后 n=n-index=2 + * 依次类推,知道 n < index 时,就无法再行程梯形了。 + * 时间复杂度应该是 O(n) 吧, + * 还有一种方式就是利用 梯形公式; + */ + +class Solution { + public int arrangeCoins(int n) { + if(n==1) + return 1; + int index = 1; + while(index<=n){ + n = n-index; + index = index+1; + if(n1->2 + * 输出: 1->2 + * 示例 2: + * 输入: 1->1->2->3->3 + * 输出: 1->2->3 +*/ + +public class DeleteDuplicateNode { + + /** + * @desc 发现上一种方法完全没有必要去那样,应为链表是已经排序好的了,并且已知前一个节点的当前的节点,可以直接进行比较 + * @annotation 注意在head为 null 的情况和链表只有一个节点的情况 + * @param head + * @return + */ + public static ListNode deleteDuplicatesV1(ListNode head) { + if (head == null || head.next == null) + return head; + ListNode current = head; + ListNode pre = null; + while (current != null) { + if (pre == null || pre.val != current.val) { + pre = current; // 保存上一节点,防止断链 + current = current.next; + } else { + pre.next = current.next; + current = pre.next; + } + } + return head; + } +} diff --git a/Week_01/id_81/LeetCode_905_81.java b/Week_01/id_81/LeetCode_905_81.java new file mode 100644 index 00000000..7a97b0b5 --- /dev/null +++ b/Week_01/id_81/LeetCode_905_81.java @@ -0,0 +1,49 @@ +/* + * 给定一个非负整数数组 A,返回一个由 A 的所有偶数元素组成的数组,后面跟 A 的所有奇数元素。 +你可以返回满足此条件的任何数组作为答案。 +示例: + 输入:[3,1,2,4] + 输出:[2,4,3,1] + 输出 [4,2,3,1],[2,4,1,3] 和 [4,2,1,3] 也会被接受。 +提示: + 1 <= A.length <= 5000 + 0 <= A[i] <= 5000 + */ +public class SortArrayByParity { + + /* + * @desc 使用两个指针分别指向数组的首尾 + */ + public static int[] sortArrayByParity(int[] A) { + if (A == null || A.length <= 1) + return A; + int start = 0; + int end = A.length - 1; + while (start < end) { + if (A[start] % 2 == 1 && A[end] % 2 == 0) { + int temp = A[start]; + A[start] = A[end]; + A[end] = temp; + start++; + end--; + } else if (A[start] % 2 == 0 && A[end] % 2 == 1) { + start++; + end--; + } else if (A[start] % 2 == 1 && A[end] % 2 == 1) { + end--; + } else if (A[start] % 2 == 0 && A[end] % 2 == 0) { + start++; + } + } + return A; + } + + public static void main(String[] args) { + int[] array = new int[] { 1, 2, 3, 4, 5, 6 }; + sortArrayByParity(array); + for (int item : array) { + System.out.print(item + " "); + } + + } +} diff --git a/Week_01/id_81/LeetCode_922_81.java b/Week_01/id_81/LeetCode_922_81.java new file mode 100644 index 00000000..ff263154 --- /dev/null +++ b/Week_01/id_81/LeetCode_922_81.java @@ -0,0 +1,33 @@ +/** + * @author apple + */ +public class SortArrayByParityII { + + /** + * 空间换时间; 时间复杂度 O(n), 空间复杂度 O(n) + * + * @param A + * @return + */ + public static int[] sortArrayByParityII(int[] A) { + if (A == null || A.length <= 1) + return A; + int len = A.length; + int[] arr = new int[len]; + + int odd = 0; + int even = 1; + for (int i = 0; i < len; ++i) { + // 奇数 + if (A[i] % 2 == 0) { + arr[odd] = A[i]; + odd = odd + 2; + // 偶数 + } else { + arr[even] = A[i]; + even = even + 2; + } + } + return arr; + } +} diff --git "a/Week_01/id_82/\344\272\214\345\217\211\346\240\221/LeetCode_236_82.java" "b/Week_01/id_82/\344\272\214\345\217\211\346\240\221/LeetCode_236_82.java" new file mode 100644 index 00000000..f32962d4 --- /dev/null +++ "b/Week_01/id_82/\344\272\214\345\217\211\346\240\221/LeetCode_236_82.java" @@ -0,0 +1,10 @@ + static BinaryTree.TreeNode lowestCommonAncestor(BinaryTree.TreeNode root, BinaryTree.TreeNode p, BinaryTree.TreeNode q) { + if (root == p) return p; + if (root == q) return q; + if (root.left != null && root.right != null){ + if ((BinaryTree.isHave(root.left, p) && BinaryTree.isHave(root.right, q)) || (BinaryTree.isHave(root.right, p) && BinaryTree.isHave(root.left, q))) return root; + if (BinaryTree.isHave(root.left, p) && BinaryTree.isHave(root.left, q)) return lowestCommonAncestor(root.left, p, q); + if (BinaryTree.isHave(root.right, p) && BinaryTree.isHave(root.right, q)) return lowestCommonAncestor(root.right, p, q); + } + return null; + } diff --git "a/Week_01/id_82/\344\272\214\345\217\211\346\240\221/LeetCode_267_82.java" "b/Week_01/id_82/\344\272\214\345\217\211\346\240\221/LeetCode_267_82.java" new file mode 100644 index 00000000..89391e5b --- /dev/null +++ "b/Week_01/id_82/\344\272\214\345\217\211\346\240\221/LeetCode_267_82.java" @@ -0,0 +1,32 @@ +static int findSecondMinimumValue(BinaryTree.TreeNode root) { + Queue queue = new LinkedList<>(); + queue.add(Integer.MAX_VALUE); + queue.add(Integer.MAX_VALUE); + Stack s = new Stack<>(); + BinaryTree.TreeNode p = root; + while (p != null || !s.isEmpty()) { + while (p != null) { + if (p.val < queue.peek()) { + int head = queue.poll(); //get the head. + if (p.val > queue.peek()) { + int tmp = queue.poll(); + queue.add(p.val); + queue.add(tmp); + } else if (p.val < queue.peek()) { + queue.add(p.val); + } else { + queue.add(head); + int tmp = queue.poll(); + queue.add(tmp); + } + + } + s.push(p); + p = p.left; + } + p = s.pop(); + p = p.right; + } + if (queue.peek() == Integer.MAX_VALUE) return -1; + else return queue.poll(); + } \ No newline at end of file diff --git "a/Week_01/id_82/\344\272\214\345\217\211\346\240\221/Main.java" "b/Week_01/id_82/\344\272\214\345\217\211\346\240\221/Main.java" new file mode 100644 index 00000000..bb637289 --- /dev/null +++ "b/Week_01/id_82/\344\272\214\345\217\211\346\240\221/Main.java" @@ -0,0 +1,174 @@ + + +import java.util.*; + +public class Main { + + public static void main(String[] args) { +// Output.printf(Solution.findSecondMinimumValue(Input.getBinaryTree())); +/* BinaryTree.TreeNode root = Input.getBinaryTree(); + int p = Input.getPositionOrK(); + int q = Input.getPositionOrK(); + Output.printf(Solution.lowestCommonAncestor(root, BinaryTree.findNode(root, p), BinaryTree.findNode(root, q)).val); + */ + + + + + } + +} + + + +class Solution { + + static int findSecondMinimumValue(BinaryTree.TreeNode root) { + Queue queue = new LinkedList<>(); + queue.add(Integer.MAX_VALUE); + queue.add(Integer.MAX_VALUE); + Stack s = new Stack<>(); + BinaryTree.TreeNode p = root; + while (p != null || !s.isEmpty()) { + while (p != null) { + if (p.val < queue.peek()) { + int head = queue.poll(); //get the head. + if (p.val > queue.peek()) { + int tmp = queue.poll(); + queue.add(p.val); + queue.add(tmp); + } else if (p.val < queue.peek()) { + queue.add(p.val); + } else { + queue.add(head); + int tmp = queue.poll(); + queue.add(tmp); + } + + } + s.push(p); + p = p.left; + } + p = s.pop(); + p = p.right; + } + if (queue.peek() == Integer.MAX_VALUE) return -1; + else return queue.poll(); + } + + static BinaryTree.TreeNode lowestCommonAncestor(BinaryTree.TreeNode root, BinaryTree.TreeNode p, BinaryTree.TreeNode q) { + if (root == p) return p; + if (root == q) return q; + if (root.left != null && root.right != null){ + if ((BinaryTree.isHave(root.left, p) && BinaryTree.isHave(root.right, q)) || (BinaryTree.isHave(root.right, p) && BinaryTree.isHave(root.left, q))) return root; + if (BinaryTree.isHave(root.left, p) && BinaryTree.isHave(root.left, q)) return lowestCommonAncestor(root.left, p, q); + if (BinaryTree.isHave(root.right, p) && BinaryTree.isHave(root.right, q)) return lowestCommonAncestor(root.right, p, q); + } + return null; + } + +/* public List distanceK(BinaryTree.TreeNode root, BinaryTree.TreeNode target, int K) { + List list = new ArrayList<>(); + + if(root==null) return null; + Queue q=new LinkedList<>(); + q.add(root); + while(!q.isEmpty()){ + BinaryTree.TreeNode temp = q.poll(); + temp + if(temp.left!=null)q.add(temp.left); + if(temp.right!=null)q.add(temp.right); + } + + + } + */ +} + + +/* Here is Supporting class + Name: BinaryTree + */ +class BinaryTree{ + public static class TreeNode { + int val; + TreeNode left; + TreeNode right; + TreeNode(int x) { val = x; } + } + + private TreeNode root; + BinaryTree(){ + root = null; + } + BinaryTree(TreeNode node){ + root = node; + } + + static TreeNode creatTree(int[] array, int index){ + TreeNode root = new TreeNode(array[index]); + if(2 * index + 1 < array.length && array[2 * index + 1] != -1) { //Array boundary judgement. + root.left = creatTree(array, 2 * index + 1); + } + if (2 * index + 1 < array.length && array[2 * index + 2] != -1) { + root.right = creatTree(array, 2 * index + 2 ); + } + return root; + } + static TreeNode findNode(TreeNode root, int key){ + TreeNode node = null; + if (root.val == key) node = root; + if (node == null && root.left != null) node = findNode(root.left, key); + if (node == null && root.right != null) node = findNode(root.right, key); + return node; + } + static Boolean isHave(TreeNode root, TreeNode node){ + Boolean flagLeft, flagRight; + flagLeft = flagRight = false; + if (root == node) return true; + if (root.left != null) flagLeft = isHave(root.left, node); + if (root.right != null) flagRight = isHave(root.right, node); + return flagLeft | flagRight; + } + + +} + + +/* Here is Interface class + Name: Output Input + */ +class Output{ +/* static void printf(HeadList.ListNode head){ + HeadList.ListNode tmp = head; + while (tmp.next != null){ + System.out.print(tmp.next.val); + tmp = tmp.next; + + } + } + */ + static void printf(int val){ + System.out.print(val); + } +} + +/* Here is Interface class + Name: ListNode + */ +class Input{ + static BinaryTree.TreeNode getBinaryTree(){ + Scanner sc = new Scanner(System.in); + int level = sc.nextInt(); + int[] array = new int[(int)Math.pow(2,level) - 1]; + for (int i = 0; i < array.length; i++){ + array[i] = sc.nextInt(); + } + return BinaryTree.creatTree(array, 0); + } + static int getPositionOrK(){ + Scanner sc = new Scanner(System.in); + return sc.nextInt(); + } +} + diff --git "a/Week_01/id_82/\344\272\214\345\217\211\346\240\221/ReadMe.md" "b/Week_01/id_82/\344\272\214\345\217\211\346\240\221/ReadMe.md" new file mode 100644 index 00000000..b3f191f5 --- /dev/null +++ "b/Week_01/id_82/\344\272\214\345\217\211\346\240\221/ReadMe.md" @@ -0,0 +1,3 @@ +以上是关于二叉树的前两道问题的解。 +Main.java是以上方法实现的全部调用类,可以直接测试。 +但是没有测试模块,欢迎指正错误。 diff --git "a/Week_01/id_82/\351\223\276\350\241\250/LeetCode_142_82.java" "b/Week_01/id_82/\351\223\276\350\241\250/LeetCode_142_82.java" new file mode 100644 index 00000000..dc4ef0d0 --- /dev/null +++ "b/Week_01/id_82/\351\223\276\350\241\250/LeetCode_142_82.java" @@ -0,0 +1,14 @@ + static HeadList.ListNode detectCycle(HeadList.ListNode head){ + Map map = new HashMap<>(); + HeadList.ListNode tmp = head; + int pos = 0; + while (tmp != null){ //JC: tmp.next == null + if (map.get(tmp) == null){ //JC: map.get() return something + map.put(tmp,pos); + tmp = tmp.next; + pos++; + } + else break; + } + return tmp; + } diff --git "a/Week_01/id_82/\351\223\276\350\241\250/LeetCode_21_82.java" "b/Week_01/id_82/\351\223\276\350\241\250/LeetCode_21_82.java" new file mode 100644 index 00000000..e19dc14a --- /dev/null +++ "b/Week_01/id_82/\351\223\276\350\241\250/LeetCode_21_82.java" @@ -0,0 +1,28 @@ + static HeadList.ListNode mergeTwoLists(HeadList.ListNode l1, HeadList.ListNode l2){ + HeadList list = new HeadList(); + HeadList.ListNode tmp1 = l1.next; //because of head node. + HeadList.ListNode tmp2 = l2.next; + while (true){ + if (tmp1 == null){ + for( ; tmp2 != null; tmp2 = tmp2.next){ + list.insert(tmp2.val); + } + break; + } + else if (tmp2 == null){ + for( ; tmp1 != null; tmp1 = tmp1.next){ + list.insert(tmp1.val); + } + break; + } + else if (tmp1.val > tmp2.val){ + list.insert(tmp2.val); + tmp2 = tmp2.next; + } + else { + list.insert(tmp1.val); + tmp1 = tmp1.next; + } + } + return list.getHead(); + } diff --git "a/Week_01/id_82/\351\223\276\350\241\250/LeetCode_24_82.java" "b/Week_01/id_82/\351\223\276\350\241\250/LeetCode_24_82.java" new file mode 100644 index 00000000..19c65737 --- /dev/null +++ "b/Week_01/id_82/\351\223\276\350\241\250/LeetCode_24_82.java" @@ -0,0 +1,15 @@ + static HeadList.ListNode swapPairs(HeadList.ListNode head){ + HeadList.ListNode pre, tmp, tail; + pre = head; + while (true){ + if (pre.next == null) break; + if (pre.next.next == null) break; + tmp = pre.next; + tail = pre.next.next.next; + pre.next = pre.next.next; + pre.next.next = tmp; + tmp.next = tail; + pre = pre.next.next; + } + return head; + } diff --git "a/Week_01/id_82/\351\223\276\350\241\250/LeetCode_25_82.java" "b/Week_01/id_82/\351\223\276\350\241\250/LeetCode_25_82.java" new file mode 100644 index 00000000..6b266f99 --- /dev/null +++ "b/Week_01/id_82/\351\223\276\350\241\250/LeetCode_25_82.java" @@ -0,0 +1,34 @@ + static HeadList.ListNode reverseKGroup(HeadList.ListNode head, int k){ + if(k == 1 || k == 0) return head; + HeadList.ListNode detect, pre, segPre, segTmp, tail, tailNext; + if (head.next == null) return head; + segPre = head; + detect = pre = segTmp = head.next; + if (head.next.next == null) return head; + tail = pre.next; + tailNext = tail.next; + while (true){ + int i = 0; + for ( ; i < k; i++){ + if (detect == null){ + segPre.next = tailNext; + return head; + } + else detect = detect.next; + } + for (int j = 0; j < k - 1; j++){ //K-1:N elements need N reverses. + tail.next = pre; + pre = tail; + + tail = tailNext; + if (tailNext != null) tailNext = tailNext.next; + + } + segPre.next = pre; + pre = tail; + tail = tailNext; + if (tailNext != null) tailNext = tailNext.next; + segPre = segTmp; + segTmp = pre; + } + } diff --git "a/Week_01/id_82/\351\223\276\350\241\250/LeetCode_83_82.java" "b/Week_01/id_82/\351\223\276\350\241\250/LeetCode_83_82.java" new file mode 100644 index 00000000..1cce7437 --- /dev/null +++ "b/Week_01/id_82/\351\223\276\350\241\250/LeetCode_83_82.java" @@ -0,0 +1,12 @@ +static HeadList.ListNode deleteDuplicates(HeadList.ListNode head) { + Map map = new HashMap<>(); + HeadList.ListNode tmp = head; + while (tmp != null){ //JC: tmp.next == null + if(map.get(tmp.val) == null){ //JC: map.get() return something + map.put(tmp.val,tmp); + } + else HeadList.delete(head,tmp); + tmp = tmp.next; + } + return head; + } \ No newline at end of file diff --git "a/Week_01/id_82/\351\223\276\350\241\250/Main.java" "b/Week_01/id_82/\351\223\276\350\241\250/Main.java" new file mode 100644 index 00000000..c3f9a6d8 --- /dev/null +++ "b/Week_01/id_82/\351\223\276\350\241\250/Main.java" @@ -0,0 +1,238 @@ + +import java.util.HashMap; +import java.util.Map; +import java.util.Scanner; + +public class Main { + + public static void main(String[] args) { +// Output.printf(Solution.deleteDuplicates(Input.getHeadList().getHead())); +// Output.printf(Solution.mergeTwoLists(Input.getHeadList().getHead(),Input.getHeadList().getHead())); +// Output.printf(Solution.swapPairs(Input.getHeadList().getHead())); +// HeadList list = Input.getHeadList(); +// Output.printf(HeadList.searchNode(Solution.detectCycle(HeadList.createCycle(Input.getPositionOrK(),list)),list)); +// Output.printf(Solution.reverseKGroup(Input.getHeadList().getHead(),Input.getPositionOrK())); + + + } + +} + +/* Here is Interface class + Name: ListNode + */ +class Solution{ + static HeadList.ListNode deleteDuplicates(HeadList.ListNode head) { + Map map = new HashMap<>(); + HeadList.ListNode tmp = head; + while (tmp != null){ //JC: tmp.next == null + if(map.get(tmp.val) == null){ //JC: map.get() return something + map.put(tmp.val,tmp); + } + else HeadList.delete(head,tmp); + tmp = tmp.next; + } + return head; + } + static HeadList.ListNode mergeTwoLists(HeadList.ListNode l1, HeadList.ListNode l2){ + HeadList list = new HeadList(); + HeadList.ListNode tmp1 = l1.next; //because of head node. + HeadList.ListNode tmp2 = l2.next; + while (true){ + if (tmp1 == null){ + for( ; tmp2 != null; tmp2 = tmp2.next){ + list.insert(tmp2.val); + } + break; + } + else if (tmp2 == null){ + for( ; tmp1 != null; tmp1 = tmp1.next){ + list.insert(tmp1.val); + } + break; + } + else if (tmp1.val > tmp2.val){ + list.insert(tmp2.val); + tmp2 = tmp2.next; + } + else { + list.insert(tmp1.val); + tmp1 = tmp1.next; + } + } + return list.getHead(); + } + static HeadList.ListNode swapPairs(HeadList.ListNode head){ + HeadList.ListNode pre, tmp, tail; + pre = head; + while (true){ + if (pre.next == null) break; + if (pre.next.next == null) break; + tmp = pre.next; + tail = pre.next.next.next; + pre.next = pre.next.next; + pre.next.next = tmp; + tmp.next = tail; + pre = pre.next.next; + } + return head; + } + static HeadList.ListNode detectCycle(HeadList.ListNode head){ + Map map = new HashMap<>(); + HeadList.ListNode tmp = head; + int pos = 0; + while (tmp != null){ //JC: tmp.next == null + if (map.get(tmp) == null){ //JC: map.get() return something + map.put(tmp,pos); + tmp = tmp.next; + pos++; + } + else break; + } + return tmp; + } + static HeadList.ListNode reverseKGroup(HeadList.ListNode head, int k){ + if(k == 1 || k == 0) return head; + HeadList.ListNode detect, pre, segPre, segTmp, tail, tailNext; + if (head.next == null) return head; + segPre = head; + detect = pre = segTmp = head.next; + if (head.next.next == null) return head; + tail = pre.next; + tailNext = tail.next; + while (true){ + int i = 0; + for ( ; i < k; i++){ + if (detect == null){ + segPre.next = tailNext; + return head; + } + else detect = detect.next; + } + for (int j = 0; j < k - 1; j++){ //K-1:N elements need N reverses. + tail.next = pre; + pre = tail; + + tail = tailNext; + if (tailNext != null) tailNext = tailNext.next; + + } + segPre.next = pre; + pre = tail; + tail = tailNext; + if (tailNext != null) tailNext = tailNext.next; + segPre = segTmp; + segTmp = pre; + } + } +} + + +/* Here is Supporting class + Name: HeadList + */ +class HeadList{ + static class ListNode{ + int val; + ListNode next; + ListNode(int x){ + val = x; + } + } + private ListNode head; + + HeadList() { + head = new ListNode(Integer.MIN_VALUE); + } + + ListNode getHead(){ + return this.head; + } + static boolean delete(ListNode head,ListNode node){ + if (head == null || node == null) return false; + ListNode tmp = head; + while (tmp.next != node && tmp.next != null){ //JC: tmp.next == node || tmp.next == null + tmp = tmp.next; + } + if (tmp.next == node){ + tmp.next = node.next; + return true; + } + else return false; + } + void insert(int x){ + ListNode tmp = new ListNode(x); + ListNode tail = head; + while (tail.next !=null){ + tail = tail.next; + } + tail.next = tmp; + } + static ListNode createCycle(int pos, HeadList list){ + ListNode tail = list.head; + while (tail.next !=null){ //get tail node. + tail = tail.next; + } + ListNode pre = list.head; + while (true){ + for (int i = 0; i < pos+1; i++){ //because of the head node. + pre = pre.next; + } + break; + } + tail.next = pre; + return list.head; + } + static int searchNode(ListNode node, HeadList list){ + ListNode tmp = list.head; + int index = 0; + while (node != tmp){ //JC: node == tmp + if (tmp != null){ + tmp = tmp.next; + index++; + } + else return -1; + } + return index - 1; + } + + +} + + +/* Here is Interface class + Name: Output Input + */ +class Output{ + static void printf(HeadList.ListNode head){ + HeadList.ListNode tmp = head; + while (tmp.next != null){ + System.out.print(tmp.next.val); + tmp = tmp.next; + + } + } + static void printf(int val){ + System.out.print(val); + } +} +class Input{ + static HeadList getHeadList(){ + Scanner sc = new Scanner(System.in); + int length = sc.nextInt(); + int[] array = new int[length]; + for (int i = 0; i < array.length; i++){ + array[i] = sc.nextInt(); + } + HeadList list = new HeadList(); + for (int i : array){ + list.insert(i); + } + return list; + } + static int getPositionOrK(){ + Scanner sc = new Scanner(System.in); + return sc.nextInt(); + } +} + diff --git "a/Week_01/id_82/\351\223\276\350\241\250/ReadMe.md" "b/Week_01/id_82/\351\223\276\350\241\250/ReadMe.md" new file mode 100644 index 00000000..db46cbeb --- /dev/null +++ "b/Week_01/id_82/\351\223\276\350\241\250/ReadMe.md" @@ -0,0 +1,3 @@ +以上是关于链表的五道问题的解。 +Main.java是以上方法实现的全部调用类。 +但是没有测试模块,欢迎指正错误。 diff --git a/Week_01/id_83/LeetCode_83_324.swift b/Week_01/id_83/LeetCode_83_324.swift new file mode 100644 index 00000000..34ff4bd8 --- /dev/null +++ b/Week_01/id_83/LeetCode_83_324.swift @@ -0,0 +1,58 @@ +// +// LeetCode324WiggleSort.swift +// AlgorithmPractice +// +// Created by Ryeagler on 2019/4/22. +// Copyright © 2019 Ryeagle. All rights reserved. +// + +import Foundation + +struct LeetCode324WiggleSort { + func wiggleSort(_ nums: inout [Int]) { + guard nums.count >= 2 else { + return + } + + for i in stride(from: 1, to: nums.count, by: 2) { + let idx = getLargest(nums, i - 1, i , i + 1) + (nums[i], nums[idx]) = (nums[idx], nums[i]) + } + } + + private func getLargest(_ nums: [Int], _ x: Int, _ y: Int, _ z: Int) -> Int { + let len = nums.count + + let xVal = x >= 0 && x < len ? nums[x] : Int.min + let yVal = y >= 0 && y < len ? nums[y] : Int.min + let zVal = z >= 0 && z < len ? nums[z] : Int.min + let maxVal = max(xVal, yVal, zVal) + + if maxVal == xVal { + return x + } else if maxVal == yVal { + return y + } else { + return z + } + } + + func wiggleSort1(_ nums: inout [Int]) { + let temp = nums.sorted() + + var m = temp.count + var n = (m + 1) / 2 + + for i in 0.. Double { + var x = x + var n = n + if n == 0 { + return 1; + } + if n < 0 { + n = -n; + x = 1 / x; + } + return ( n % 2 == 0) ? myPow(x * x, n / 2) : x * myPow(x * x, n / 2); + } +} diff --git a/Week_01/id_83/NOTE.md b/Week_01/id_83/NOTE.md index c684e62f..7a10e4bc 100644 --- a/Week_01/id_83/NOTE.md +++ b/Week_01/id_83/NOTE.md @@ -1 +1,5 @@ -# 学习笔记 \ No newline at end of file +# 学习笔记 + +贵有恒,何必三更起五更眠 + +最无益,只怕一日曝十日寒 \ No newline at end of file diff --git a/Week_01/id_84/LeetCode_25_84.java b/Week_01/id_84/LeetCode_25_84.java new file mode 100644 index 00000000..0a0cf6e1 --- /dev/null +++ b/Week_01/id_84/LeetCode_25_84.java @@ -0,0 +1,83 @@ +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode(int x) { val = x; } + * } + */ +//思路:每遇到k个元素,就将原链段成子链,然后对断开的子链进行逆序。再合并。 +class Solution { + int length = 0; + + public ListNode reverseKGroup(ListNode head, int k) { + length = this.ListLength(head); + if ( length == 1 || k > length ) return head; + //如果k=length,直接反转 + if(length == k){ + return reverseList(head); + } + + ListNode p1 = head; //p1为遍历指针 + ListNode p2 = head; //p2为指向子链 + int count = 1; + head = null; + while ( count <= length) { + if (count % k != 0){ + p1 = p1.next; + } + + else { + + ListNode temp = p1; + p1 = p1.next; + temp.next = null; + temp = head; + head = reverseList(p2); + //head = mergeList(head, p1); + head = mergeList(temp,head); + p2 = p1; + + } + ++count; + + + } + mergeList(head,p2); + return head; + } +// 链表长度 + public int ListLength(ListNode head) { + int length = 0; + if(head == null ){ return length;} + while (head.next != null) { + ++length; + head = head.next; + } + return length + 1; + } +//反转链表 + public ListNode reverseList(ListNode head) { + if (head == null) return null; + if (head.next == null) return head; + ListNode p = reverseList(head.next);; + head.next.next = head; + head.next = null; + return p; + + } +//合并两个链表 + public ListNode mergeList(ListNode head1, ListNode head2) { + ListNode temp = head1; + if (temp != null) { + while (head1.next != null) { + head1 = head1.next; + } + head1.next = head2; + return temp; + } + else return head2; + } + + +} \ No newline at end of file diff --git a/Week_01/id_84/LeetCode_905_84.java b/Week_01/id_84/LeetCode_905_84.java new file mode 100644 index 00000000..11f6b739 --- /dev/null +++ b/Week_01/id_84/LeetCode_905_84.java @@ -0,0 +1,21 @@ +public class LeetCode_905_84 { + public int[] sortArrayByParity(int[] A) { + int length = A.length; + if (length == 0) { + return A; + } + int B[] = new int[length]; + int low = 0; + int high = length - 1; + for (int i = 0; i < length; i++) { + if (A[i] % 2 == 0) { + B[low++] = A[i]; + } + else { + B[high--] = A[i]; + } + } + return B; + + } +} diff --git a/Week_01/id_85/LeetCode_142_85.java b/Week_01/id_85/LeetCode_142_85.java new file mode 100644 index 00000000..4564d984 --- /dev/null +++ b/Week_01/id_85/LeetCode_142_85.java @@ -0,0 +1,91 @@ +import java.util.HashMap; + +public class LeetCode_142_85 { + +} +/** + * @Package: + * @ClassName: LeetCode_142_85.LinkedListCycleII + * @Description: 给定一个链表,返回链表开始入环的第一个结点。 如果链表无环,则返回 null 难度:中 + * @leetCode url : https://leetcode.com/problems/linked-list-cycle-ii/ + * @Author: wangzhao + * @Date: 2019-04-16 13:24:35 + * @Version: 1.0.0 + * @Since: 1.8 + **/ +class LinkedListCycleII { + + /** + * + * 利用哈希表保存已出现的结点, + * 如果该结点存在,则返回该结点 + * + */ + public ListNode detectCycle(ListNode head) { + if (head==null){ + return head; + } + HashMap map = new HashMap<>(); + while (head.next!=null){ + + if (map.get(head)!=null){ + return head; + }else { + map.put(head,1); + } + head = head.next; + } + + + return null; + } + + public ListNode detectCycle2(ListNode head) { + if (head==null){ + return null; + } + + return null; + } + + + public static void main(String[] args) { + Integer[] arr = {0, 1, 2, 3, 4, 6, 7, 8}; + + //初始化一个无用结点。去除边界问题 + ListNode cur = new ListNode(-1); + ListNode head = cur; + + ListNode cycleNode = null; + + for (int i = 0; i < arr.length; i++) { + + cur.next = new ListNode(arr[i]); + if (i == 4) { + //摘取入环结点 + cycleNode = cur.next; + } + cur = cur.next; + if (i == arr.length - 1) { + //链表尾结点指向入环结点 + cur.next = cycleNode; + } + } + + + /** + * 循环去重 + */ + ListNode resultNode = new LinkedListCycleII().detectCycle(head.next); + ListNode node = head.next; + int i=-1; + while (node != null&&resultNode!=null) { + i++; + if (node==resultNode){ + break; + } + node = node.next; + } + System.out.println("入环位置:"+i); + } +} \ No newline at end of file diff --git a/Week_01/id_85/LeetCode_153_85.java b/Week_01/id_85/LeetCode_153_85.java new file mode 100644 index 00000000..0617c2bc --- /dev/null +++ b/Week_01/id_85/LeetCode_153_85.java @@ -0,0 +1,58 @@ +public class LeetCode_153_85 { +} + +/** + * @Package: + * @ClassName: ArraySortedFindMin + * @Description: ***************************************************** + * **************假设按照升序排序的数组在预先未知的某个点上进行了旋转。 + * **************( 例如,数组 [0,1,2,4,5,6,7] 可能变为 [4,5,6,7,0,1,2] )。 + * **************请找出其中最小的元素。 + * **************你可以假设数组中不存在重复元素。 难度:中 + * @leetcode url:https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/ + * @Author: wangzhao + * @Date: 2019-04-17 14:42:15 + * @Version: 1.0.0 + * @Since: 1.8 + **/ +class ArraySortedFindMin { + + public int findMin(int[] nums) { + + if (nums == null) { + return -1; + } + if (nums.length == 1) { + return nums[0]; + } + int last = nums.length - 1; + int lastVal = nums[last]; + + for (int i = 0; i < nums.length; i++) { + + if (nums[0] > nums[last]) { + lastVal = nums[last]; + last--; + continue; + } + if (nums[0] <= nums[last]) { + break; + } + } + if (nums[0] < lastVal) { + return nums[0]; + } + + return lastVal; + } + + + public static void main(String[] args) { + + int[] arr = {3, 4, 5, 1, 2}; + + int result = new ArraySortedFindMin().findMin(arr); + + System.out.println(result); + } +} diff --git a/Week_01/id_85/LeetCode_21_85.java b/Week_01/id_85/LeetCode_21_85.java new file mode 100644 index 00000000..70c18117 --- /dev/null +++ b/Week_01/id_85/LeetCode_21_85.java @@ -0,0 +1,79 @@ +public class LeetCode_21_85 { + +} +/** + * @Package: + * @ClassName: LeetCode_21_85.LinkedListSortMerge + * @Description: 有序链表合并为一个新的有序链表 + * @leetcode url :https://leetcode.com/problems/merge-two-sorted-lists + * @Author: wangzhao + * @Date: 2019-04-16 10:16:48 + * @Version: 1.0.0 + * @Since: 1.8 + **/ +class LinkedListSortMerge { + + + /** + *思路: + * 1.两个链表同时移动比较,值大的结点暂停移动,直到该结点为较小值 + */ + public ListNode mergeTwoLists(ListNode l1, ListNode l2) { + + ListNode node = new ListNode(-1); + ListNode cur = node; + while (true) { + if (l1 == null && l2 == null) { + break; + } + if (l1 == null) { + cur.next = l2; + break; + } + if (l2 == null) { + cur.next = l1; + break; + } + if (l1.val <= l2.val) { + cur.next = l1; + l1 = l1.next; + } else { + cur.next = l2; + l2 = l2.next; + } + cur = cur.next; + } + return node.next; + } + + + public static void main(String[] args) { + Integer[] arr = {0,1, 1, 3, 6, 7}; + Integer[] arr1 = {0,2, 3, 5, 6,8}; + + //初始化一个无用结点。去除边界问题 + ListNode cur = new ListNode(-1); + ListNode head1 = cur; + + for (Integer i : arr) { + cur.next = new ListNode(i); + cur = cur.next; + } + + + //初始化一个无用结点。去除边界问题 + cur = new ListNode(-1); + ListNode head2 = cur; + + for (Integer i : arr1) { + cur.next = new ListNode(i); + cur = cur.next; + } + + ListNode resultNode = new LinkedListSortMerge().mergeTwoLists(head1.next, head2.next); + while (resultNode != null) { + System.out.println(resultNode.val); + resultNode = resultNode.next; + } + } +} diff --git a/Week_01/id_85/LeetCode_24_85.java b/Week_01/id_85/LeetCode_24_85.java new file mode 100644 index 00000000..24cb07e8 --- /dev/null +++ b/Week_01/id_85/LeetCode_24_85.java @@ -0,0 +1,72 @@ +public class LeetCode_24_85 { +} +/** + * @Package: + * @ClassName: LeetCode_24_85.LinkedListSwapPairs + * @Description: 给定一个链表,两两交换其中相邻的结点 难度:中 + * @leetCode url:https://leetcode-cn.com/problems/swap-nodes-in-pairs/ + * @Author: wangzhao + * @Date: 2019-04-16 10:52:29 + * @Version: 1.0.0 + * @Since: 1.8 + **/ +class LinkedListSwapPairs { + + /** + *思路: + * 1.暂存前结点 + * 2.交换两个结点位置 + * 3.将前结点的下一结点指向交换后的两个的结点的第一个结点 + * 4.移动前结点到交换后的两个结点的第二个结点 + * 5.如果存在结点交换,并且头结点为空,保存头结点,用于函数返回 + * 6.移动head到下一对结点的第一个结点 + */ + public ListNode swapPairs(ListNode head) { + + if (head == null || head.next == null) return head; + + ListNode prev = new ListNode(-1); + ListNode result = null; + + while (head != null) { + + if (head.next == null) { + break; + } + ListNode next = head.next; + head.next = next.next; + next.next = head; + + prev.next = next; + prev = head; + + if (result == null) { + result = next; + } + + head = head.next; + + } + return result; + } + + public static void main(String[] args) { + Integer[] arr = {0, 1, 2, 3, 4, 6, 7, 8}; + + //初始化一个无用结点。去除边界问题 + ListNode cur = new ListNode(-1); + ListNode head = cur; + + for (Integer i : arr) { + cur.next = new ListNode(i); + cur = cur.next; + } + + + ListNode resultNode = new LinkedListSwapPairs().swapPairs(head.next); + while (resultNode != null) { + System.out.println(resultNode.val); + resultNode = resultNode.next; + } + } +} \ No newline at end of file diff --git a/Week_01/id_85/LeetCode_25_85.java b/Week_01/id_85/LeetCode_25_85.java new file mode 100644 index 00000000..2251a34b --- /dev/null +++ b/Week_01/id_85/LeetCode_25_85.java @@ -0,0 +1,103 @@ +public class LeetCode_25_85 { +} +/** + * @Package: + * @ClassName: LeetCode_25_85.LinkedListReverseKGroup + * @Description: 给出一个链表,每 k 个结点一组进行翻转,并返回翻转后的链表。 + * k 是一个正整数,它的值小于或等于链表的长度。如果结点总数不是 k 的整数倍,那么将最后剩余结点保持原有顺序。 + * 难度:困难 + * @leetcode url :https://leetcode.com/problems/reverse-nodes-in-k-group/ + * @Author: wangzhao + * @Date: 2019-04-16 14:35:49 + * @Version: 1.0.0 + * @Since: 1.8 + **/ +class LinkedListReverseKGroup { + + public ListNode reverseKGroup(ListNode head, int k) { + + if (head == null || k == 0) { + return null; + } + if (k == 1) { + return head; + } + + int i = 1; + + ListNode oldList = head; + + ListNode cursor = head; + + ListNode first = head; + + ListNode result = null; + + ListNode lastCursor = new ListNode(-1); + + boolean isDiv = false; + while (cursor.next != null) { + i++; + ListNode _next = cursor.next; + cursor.next = _next.next; + _next.next = first; + first = _next; + lastCursor.next = first; + + isDiv = false; + if (i % k == 0) { + lastCursor = cursor; + cursor = cursor.next; + if (result == null) { + result = first; + } + isDiv = true; + first = cursor; + i++; + if (cursor == null) { + break; + } + } + + } + if (result == null && !isDiv) { + result = oldList; + } + + if (result != null && !isDiv) { + cursor = first; + while (cursor.next != null) { + ListNode _next = cursor.next; + cursor.next = _next.next; + _next.next = first; + first = _next; + lastCursor.next = first; + } + } + + return result; + } + + + + public static void main(String[] args) { + Integer[] arr = {1, 2, 3, 4, 5, 6, 7}; + + //初始化一个无用结点。去除边界问题 + ListNode cur = new ListNode(-1); + ListNode head = cur; + + for (Integer i : arr) { + cur.next = new ListNode(i); + cur = cur.next; + } + + int k = 2; + + ListNode resultNode = new LinkedListReverseKGroup().reverseKGroup(head.next, k); + while (resultNode != null) { + System.out.println(resultNode.val); + resultNode = resultNode.next; + } + } +} \ No newline at end of file diff --git a/Week_01/id_85/LeetCode_324_85.java b/Week_01/id_85/LeetCode_324_85.java new file mode 100644 index 00000000..fa45aee2 --- /dev/null +++ b/Week_01/id_85/LeetCode_324_85.java @@ -0,0 +1,57 @@ +import java.util.Arrays; + +public class LeetCode_324_85 { +} + +/** + * @Package: + * @ClassName: WiggleSortII + * @Description: ***************************************** + * **************给定一个无序的数组 nums,将它重新排列成 nums[0] < nums[1] > nums[2] < nums[3]... 的顺序。 + * ************** 难度:中 + * @Author: wangzhao + * @Date: 2019-04-20 10:35:56 + * @Version: 1.0.0 + * @Since: 1.8 + **/ +class WiggleSortII { + + public void wiggleSort(int[] nums) { + + if (nums == null) return; + + nums = sort(nums); + int left = nums.length % 2 == 0 ? nums.length / 2 - 1 : nums.length / 2; + int right = nums.length - 1; + int[] _nums = new int[nums.length]; + for (int i = 0; i < _nums.length; i++) { + if (i % 2 == 0) { + _nums[i] = nums[left]; + left--; + } else { + _nums[i] = nums[right]; + right--; + } + } + + for (int i = 0; i < nums.length; i++) { + nums[i] = _nums[i]; + } + Arrays.stream(nums).forEach(i -> System.out.print(i + ",")); + } + + private int[] sort(int[] nums) { + //TODO:自写代码实现排序 + Arrays.sort(nums); + return nums; + } + + + public static void main(String[] args) { + + int[] nums = {1, 1, 2, 1, 2, 2, 1}; + new WiggleSortII().wiggleSort(nums); + + } +} + diff --git a/Week_01/id_85/LeetCode_33_85.java b/Week_01/id_85/LeetCode_33_85.java new file mode 100644 index 00000000..cb3e560b --- /dev/null +++ b/Week_01/id_85/LeetCode_33_85.java @@ -0,0 +1,64 @@ +public class LeetCode_33_85 { +} + +/** + * @Package: + * @ClassName: LeetCode_33_85.ArraySortedSearch + * @Description: ************************************ + * **************假设按照升序排序的数组在预先未知的某个点上进行了旋转。 + * **************( 例如,数组 [0,1,2,4,5,6,7] 可能变为 [4,5,6,7,0,1,2] )。 + * **************搜索一个给定的目标值,如果数组中存在这个目标值,则返回它的索引,否则返回 -1 。 + * **************你可以假设数组中不存在重复的元素。 + * **************算法时间复杂度必须是 O(log n) 级别。 难度:难 + * @leetcode url :https://leetcode-cn.com/problems/search-in-rotated-sorted-array + * @Author: wangzhao + * @Date: 2019-04-17 22:22:56 + * @Version: 1.0.0 + * @Since: 1.8 + **/ +class ArraySortedSearch { + + public int search(int[] nums, int target) { + + if (nums == null || nums.length == 0) { + return -1; + } + if (target == nums[0]) { + return 0; + } + if (target == nums[nums.length - 1]) { + return nums.length - 1; + } + + int left = 0, right = nums.length - 1; + while (left <= right) { + int mid = (right - left) / 2 + left; + if (nums[mid] == target) { + return mid; + } else if (nums[mid] < nums[right]) { + if (nums[mid] < target && nums[right] >= target) { + left = mid + 1; + } else { + right = mid - 1; + } + } else { + if (nums[mid] > target && nums[left] <= target) { + right = mid - 1; + } else { + left = mid + 1; + } + } + } + + return -1; + } + + + public static void main(String[] args) { + int[] nums = {7, 8, 1, 2, 3, 4, 5, 6}; + int target = 2; + + int index = new ArraySortedSearch().search(nums, target); + System.out.println(index); + } +} diff --git a/Week_01/id_85/LeetCode_503_85.java b/Week_01/id_85/LeetCode_503_85.java new file mode 100644 index 00000000..87383ae4 --- /dev/null +++ b/Week_01/id_85/LeetCode_503_85.java @@ -0,0 +1,115 @@ +import java.util.Stack; + +public class LeetCode_503_85 { +} + +/** + * @Package: + * @ClassName: NextGreaterElementII + * @Description: *************************** + * **************给定一个循环数组(最后一个元素的下一个元素是数组的第一个元素), + * **************输出每个元素的下一个更大元素。数字 x 的下一个更大的元素是按数组遍历顺序, + * **************这个数字之后的第一个比它更大的数, + * **************这意味着你应该循环地搜索它的下一个更大的数。如果不存在,则输出 -1。难度:中 + * @leetcode url:https://leetcode.com/problems/next-greater-element-ii/ + * @Author: wangzhao + * @Date: 2019-04-18 14:51:45 + * @Version: 1.0.0 + * @Since: 1.8 + **/ +class NextGreaterElementII { + + + public int[] nextGreaterElements(int[] nums) { + + if (nums == null || nums.length == 0) { + return nums; + } + int[] res = new int[nums.length]; + + for (int i = 0; i < nums.length; i++) { + int bigger = -1; + int prevIndex = -1; + int afterIndex = i; + while (true) { + afterIndex++; + if (afterIndex == nums.length) { + prevIndex++; + afterIndex--; + if (prevIndex == i) { + break; + } + if (nums[prevIndex] > nums[i]) { + bigger = nums[prevIndex]; + break; + } + } + if (nums[afterIndex] > nums[i]) { + bigger = nums[afterIndex]; + break; + } + } + res[i] = bigger; + } + + return res; + } + + /** + * 利用单调栈,存放数组下标 + */ + public int[] nextGreaterElements2(int[] nums) { + + if (nums == null || nums.length == 0) { + return nums; + } + + Stack stack = new Stack<>(); + int[] res = new int[nums.length]; + for (int i = 0; i < res.length; i++) { + res[i] = -1; + } + boolean isGoon = true; + for (int i = 0; i < nums.length; i++) { + + while (true) { + Integer n = null; + try { + n = stack.peek(); + } catch (Exception e) { + break; + } + if (nums[n] < nums[i]) { + res[n] = nums[i]; + stack.pop(); + } else { + break; + } + } + stack.push(i); + if (i == nums.length - 1 && isGoon) { + isGoon = false; + i = -1; + } else if (i == nums.length - 1 && !isGoon) { + break; + } + } + return res; + } + + public static void main(String[] args) { + + int[] arr = {5, 4, 3, 2, 1}; + + int[] res = new NextGreaterElementII().nextGreaterElements(arr); + for (int r : res) { + System.out.print(r + ","); + } + System.out.println(""); + System.out.println("----------------------------------------"); + res = new NextGreaterElementII().nextGreaterElements2(arr); + for (int r : res) { + System.out.print(r + ","); + } + } +} diff --git a/Week_01/id_85/LeetCode_50_85.java b/Week_01/id_85/LeetCode_50_85.java new file mode 100644 index 00000000..7ed57381 --- /dev/null +++ b/Week_01/id_85/LeetCode_50_85.java @@ -0,0 +1,73 @@ +public class LeetCode_50_85 { +} + +/** + * @Package: + * @ClassName: PowXN + * @Description: 实现 pow(x, n) ,即计算 x 的 n 次幂函数。 难度:中 + * @leetCode url:https://leetcode.com/problems/powx-n/ + * @Author: wangzhao + * @Date: 2019-04-20 11:56:45 + * @Version: 1.0.0 + * @Since: 1.8 + **/ +class PowXN { + + /** + * leetcode结果超时 + */ + public double myPow2(double x, int n) { + + if (n == 0) { + return 1; + } + if (x == 0) { + return 0; + } + double r = 1; + + for (int i = 0; i < (n < 0 ? -n : n); i++) { + r = r * x; + } + if (n < 0) { + return 1 / r; + } else { + return r; + } + } + + public double myPow(double x, int n) { + + if (n == 0) { + return 1; + } + if (x == 0) { + return 0; + } + + if (n < 0) { + return 1 / power(x, n); + } else { + return power(x, n); + } + + } + + public double power(double x, int n) { + if (n == 0) { + return 1; + } + double result = power(x, n / 2); + if (n % 2 == 0) { + return result * result; + } else { + return result * result * x; + } + + } + + public static void main(String[] args) { + double res = new PowXN().myPow(2.00, 10); + System.out.println(res); + } +} diff --git a/Week_01/id_85/LeetCode_698_85.java b/Week_01/id_85/LeetCode_698_85.java new file mode 100644 index 00000000..17a5baaf --- /dev/null +++ b/Week_01/id_85/LeetCode_698_85.java @@ -0,0 +1,90 @@ +import java.util.Arrays; + +public class LeetCode_698_85 { +} + +/** + * @Package: + * @ClassName: RecurvePartKEqualSubsets + * @Description: ***************************** + * **************给定一个整数数组 nums 和一个正整数 k,找出是否有可能把这个数组分成 k 个非空子集,其总和都相等。 + * **************示例 1: + * **************输入: nums = [4, 3, 2, 3, 5, 2, 1], k = 4 + * **************输出: True + * **************说明: 有可能将其分成 4 个子集(5),(1,4),(2,3),(2,3)等于总和。 难度:中等 + * @leetCode url:https://leetcode.com/problems/partition-to-k-equal-sum-subsets/ + * @Author: wangzhao + * @Date: 2019-04-19 11:39:28 + * @Version: 1.0.0 + * @Since: 1.8 + **/ +class RecurvePartKEqualSubsets { + + /** + * + * 思路: + * 1.需要均分,因此全集数字之和不能为奇数, + * 2.分割子集之和等于平均数 + * 3.查看所有数字的组合是否满足第二条 + */ + public boolean canPartitionKSubsets(int[] nums, int k) { + + if (nums == null || k == 0) return false; + + if (k == 1) return true; + int sum = Arrays.stream(nums).sum(); + if (sum % k != 0) { + return false; + } + if (sum % 2 != 0 && k % 2 == 0) { + return false; + } + int avg = sum / k; + + boolean[] flagNums = new boolean[nums.length]; + + return dfs(nums, k, avg, 0, 0, flagNums); + } + + + /** + * + * @param nums 数组全集 + * @param k 分割数 + * @param avg 平均值 + * @param sum 当前计算和 + * @param nextBegin 下个开始数下标 + * @param flagNums 标记已参与计算结果和为avg的数 + * @return + */ + private boolean dfs(int[] nums, int k, int avg, int sum, int nextBegin, boolean[] flagNums) { + + if (k == 1) { + return true; + } + if (avg == sum) { + return dfs(nums, k - 1, avg, 0, 0, flagNums); + } + + for (int i = nextBegin; i < nums.length; i++) { + if (flagNums[i]) { + continue; + } + flagNums[i] = true; + if (dfs(nums, k, avg, sum + nums[i], i + 1, flagNums)) { + return true; + } + flagNums[i] = false; + } + + return false; + } + + public static void main(String[] args) { + int[] nums = {4, 3, 2, 3, 5, 2, 1}; + int k = 4; + + boolean result = new RecurvePartKEqualSubsets().canPartitionKSubsets(nums, k); + System.out.println(result); + } +} diff --git a/Week_01/id_85/LeetCode_83_85.java b/Week_01/id_85/LeetCode_83_85.java new file mode 100644 index 00000000..f3b332b3 --- /dev/null +++ b/Week_01/id_85/LeetCode_83_85.java @@ -0,0 +1,108 @@ +public class LeetCode_83_85 { +} + +/** + * @Package: + * @ClassName: LinkedListDelDup + * @Description: 删除排序链表中的重复元素 + * @leetcode url :https://leetcode.com/problems/remove-duplicates-from-sorted-list/ + * @Author: wangzhao + * @Date: 2019-04-15 15:18:28 + * @Version: 1.0.0 + * @Since: 1.8 + **/ +class LinkedListDelDup { + + + public ListNode deleteDuplicates(ListNode head) { + + if (head == null) { + return null; + } + ListNode result = head; + + while (head.next != null) { + /** + * 当前结点与下一结点值比较 + * 如果相等,则将当前结点的下一结点指向下下结点 + */ + if (head.val == head.next.val) { + head.next = head.next.next; + } + /** + * 比较当前结点与下一结点的值是否相等, + * 如果相等则当前结点不移动到下一结点 + * 循环上一步判断 + */ + if (head.next != null && head.val != head.next.val) { + head = head.next; + } + } + + return result; + } + + public ListNode deleteDuplicates2(ListNode head) { + + if (head == null || head.next == null) { + return head; + } + /** + * 取出当前结点的下一结点 + */ + ListNode next = head.next; + /** + * 判断当前结点与下一结点的值是否相等 + */ + if (head.val == next.val) { + /** + * 如果相等,将当前结点的下一结点指向下一届结点的下一结点 + */ + head.next = next.next; + /** + * 递归调用 + */ + deleteDuplicates2(head); + } else { + /** + * 当前结点与下一结点的值不相等,递归下一结点 + */ + deleteDuplicates2(next); + } + return head; + } + + + public static void main(String[] args) { + + + Integer[] arr = {1, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 5}; + + //初始化一个无用结点。去除边界问题 + ListNode cur = new ListNode(-1); + ListNode head = cur; + + for (Integer i : arr) { + cur.next = new ListNode(i); + cur = cur.next; + } + + /** + * 循环去重 + */ + ListNode resultNode = new LinkedListDelDup().deleteDuplicates(head.next); + while (resultNode != null) { + System.out.println(resultNode.val); + resultNode = resultNode.next; + } + System.out.println("----------------我是分隔符------------------"); + /** + * 递归去重 + */ + resultNode = new LinkedListDelDup().deleteDuplicates2(head.next); + while (resultNode != null) { + System.out.println(resultNode.val); + resultNode = resultNode.next; + } + } +} \ No newline at end of file diff --git a/Week_01/id_85/LeetCode_905_85.java b/Week_01/id_85/LeetCode_905_85.java new file mode 100644 index 00000000..a9cce9bd --- /dev/null +++ b/Week_01/id_85/LeetCode_905_85.java @@ -0,0 +1,77 @@ +import java.util.Random; + +public class LeetCode_905_85 { + +} + +/** + * @Package: + * @ClassName: LeetCode_905_85.ArraySortByParity + * @Description: 给定一个非负整数数组 A,返回一个由 A 的所有偶数元素组成的数组,后面跟 A 的所有奇数元素。 难度:简单 + * @leetcode url:https://leetcode.com/problems/sort-array-by-parity/ + * @Author: wangzhao + * @Date: 2019-04-17 10:18:20 + * @Version: 1.0.0 + * @Since: 1.8 + **/ +class ArraySortByParity { + + public int[] sortArrayByParity(int[] A) { + + if (A == null) return null; + int prev = 0; + int last = A.length - 1; + + for (int i = 0; i < A.length; i++) { + + if (prev >= last) { + break; + } + if (A[prev] % 2 != 0 && A[last] % 2 == 0) { + int temp = A[prev]; + A[prev] = A[last]; + A[last] = temp; + prev++; + last--; + continue; + } + if (A[prev] % 2 == 0 && A[last] % 2 == 0) { + prev++; + continue; + } + if (A[prev] % 2 != 0 && A[last] % 2 != 0) { + last--; + continue; + } + if (A[prev] % 2 == 0 && A[last] % 2 != 0) { + prev++; + continue; + } + + } + return A; + } + + + public static void main(String[] args) { + int[] arr = new int[10]; + + Random r = new Random(); + for (int i = 0; i < arr.length; i++) { + + int a = r.nextInt(100); + System.out.print(a + ","); + + arr[i] = a; + } + System.out.println(""); + System.out.println("-----------我是分割线-------------"); + int[] arr2 = {0, 1, 2, 3}; + int[] result = new ArraySortByParity().sortArrayByParity(arr2); + for (int i : result) { + System.out.print(i + ","); + } + + + } +} \ No newline at end of file diff --git a/Week_01/id_85/ListNode.java b/Week_01/id_85/ListNode.java new file mode 100644 index 00000000..94f18861 --- /dev/null +++ b/Week_01/id_85/ListNode.java @@ -0,0 +1,8 @@ +class ListNode { + int val; + ListNode next; + + ListNode(int x) { + val = x; + } +} diff --git a/Week_01/id_85/NOTE.md b/Week_01/id_85/NOTE.md index c684e62f..e2219793 100644 --- a/Week_01/id_85/NOTE.md +++ b/Week_01/id_85/NOTE.md @@ -1 +1,37 @@ -# 学习笔记 \ No newline at end of file +# 学习笔记 +第一周题目 + +链表 +简单:https://leetcode-cn.com/problems/remove-duplicates-from-sorted-list/ ==> 完成 LeetCode_83_85.java +简单:https://leetcode-cn.com/problems/merge-two-sorted-lists ==> 完成 LeetCode_21_85.java +中等:https://leetcode-cn.com/problems/swap-nodes-in-pairs/ ==> 完成 LeetCode_24_85.java +中等:https://leetcode-cn.com/problems/linked-list-cycle-ii ==> 完成 LeetCode_142_85.java +困难:https://leetcode-cn.com/problems/reverse-nodes-in-k-group/ ==> 完成 LeetCode_25_85.java + +数组 +简单:https://leetcode-cn.com/problems/sort-array-by-parity/ ==>完成 LeetCode_905_85.java +简单:https://leetcode-cn.com/problems/sort-array-by-parity-ii/ +中等:https://leetcode-cn.com/problems/search-in-rotated-sorted-array-ii/ +中等:https://leetcode-cn.com/problems/find-minimum-in-rotated-sorted-array/ ==>完成 LeetCode_153_85.java +困难:https://leetcode-cn.com/problems/search-in-rotated-sorted-array ==>完成 LeetCode_33_85.java + +栈 +简单:https://leetcode-cn.com/problems/valid-parentheses/ +中等:https://leetcode-cn.com/problems/next-greater-element-ii/ ==>完成 LeetCode_503_85.java +困难:https://leetcode-cn.com/problems/maximum-frequency-stack/ + +递归 +简单:https://leetcode-cn.com/problems/longest-univalue-path/ +中等:https://leetcode-cn.com/problems/partition-to-k-equal-sum-subsets/ ==> 完成 LeetCode_698_85.java +困难:https://leetcode-cn.com/problems/special-binary-string/ + +排序 +简单:https://leetcode-cn.com/problems/valid-anagram/ +中等:https://leetcode-cn.com/problems/wiggle-sort-ii/ ==> 完成 LeetCode_324_85.java +困难:https://leetcode-cn.com/problems/maximum-gap/ + +二分查找 +简单:https://leetcode-cn.com/problems/arranging-coins/ +中等:https://leetcode-cn.com/problems/powx-n/ ==> 完成 LeetCode_50_85.java +困难:https://leetcode-cn.com/problems/dungeon-game/ + diff --git a/Week_01/id_86/LeetCode_083_086.c b/Week_01/id_86/LeetCode_083_086.c new file mode 100644 index 00000000..14ff68ee --- /dev/null +++ b/Week_01/id_86/LeetCode_083_086.c @@ -0,0 +1,24 @@ +//simple C + +void MethodFor083_1(struct ListNode* head) +{ + if (head == NULL) + { + return NULL; + } + struct ListNode *p, *q; + p = head; + while (p->next) + { + q = p->next; + if (p->val == q->val) + { + p->next = q->next; + } + else + { + p = q; + } + } + return head; +} \ No newline at end of file diff --git a/Week_01/id_86/LeetCode_083_086.cs b/Week_01/id_86/LeetCode_083_086.cs new file mode 100644 index 00000000..2e01c148 --- /dev/null +++ b/Week_01/id_86/LeetCode_083_086.cs @@ -0,0 +1,41 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AlgorithmTest +{ + public class LeetCode_083_086 + { + ///

+ /// 92ms 23.9MB + /// + /// + /// + public ListNode MethodFor093_1(ListNode head) + { + if (head == null) + return null; + if (head.next == null) + return head; + else + { + ListNode listNode = head; + while (listNode.next != null) + { + if (listNode.next.val == listNode.val) + { + listNode.next = listNode.next.next; + } + else + { + listNode = listNode.next; + } + } + } + + return head; + } + } +} diff --git a/Week_01/id_86/LeetCode_083_086.py b/Week_01/id_86/LeetCode_083_086.py new file mode 100644 index 00000000..5590e3d9 --- /dev/null +++ b/Week_01/id_86/LeetCode_083_086.py @@ -0,0 +1,14 @@ + +class Solution(object): + def RemoveDuplicatesfromSortedList(self, head): + """ + :type head: ListNode + :rtype: ListNode + """ + cur = head + while cur and cur.next: + if cur.val == cur.next.val: + cur.next = cur.next.next + else: + cur = cur.next + return head \ No newline at end of file diff --git a/Week_01/id_86/LeetCode_905_086.c b/Week_01/id_86/LeetCode_905_086.c new file mode 100644 index 00000000..3f4f7415 --- /dev/null +++ b/Week_01/id_86/LeetCode_905_086.c @@ -0,0 +1,22 @@ +//simple C + +int* MethodFor905_1(int* A, int ASize, int* BSize) +{ + int e = 0; + int o = ASize - 1; + int *B = (int *)malloc(sizeof(int) * ASize); + + for (int i = 0; i < ASize; i++) + { + if (A[i] % 2 == 0) + { + B[e++] = A[i]; + } + else + { + B[o--] = A[i]; + } + } + *BSize = ASize; + return B; +} \ No newline at end of file diff --git a/Week_01/id_86/LeetCode_905_086.cs b/Week_01/id_86/LeetCode_905_086.cs new file mode 100644 index 00000000..ab830dae --- /dev/null +++ b/Week_01/id_86/LeetCode_905_086.cs @@ -0,0 +1,82 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AlgorithmTest +{ + /// + /// 905. Sort Array By Parity + /// Given an array A of non-negative integers, return an array consisting of all the even elements of A, followed by all the odd elements of A.You may return any answer array that satisfies this condition. + /// + public class LeetCode_905 + { + /// + /// 思路:第一个检查是否是奇数,如果是的话和最后一个交换,在进行检测是否是奇数,和倒数第二个交换,以此往后,到i=n-flag时截止 + /// + /// 260 ms 31.9MB + /// + /// + public int[] MethodFor905_1(int[] A) + { + int n = A.Length; + int temp; + int flag = 1; + + for (int i = 0; i < n ; i++) + { + if (A[i] % 2 == 1) + { + temp = A[i]; + A[i] = A[n - flag]; + A[n - flag] = temp; + + flag++; + i--; + } + if (i==n-flag) { break; } + } + return A; + } + + /// + /// 参考 + /// + /// + /// + public int[] MethodFor905_2(int[] A) + { + int l = 0; + int r = A.Length - 1; + while (l < r) + { + while (l < r && A[l] % 2 == 0) + { + l++; + } + while (l < r && A[r] % 2 == 1) + { + r--; + } + if (l < r) + { + int temp = A[l]; + A[l] = A[r]; + A[r] = temp; + } + } + return A; + } + + /// + /// 参考 + /// + /// + /// + public int[] MethodFor905_3(int[] A) + { + return A.Where(x => x % 2 == 0).Concat(A.Where(x => x % 2 != 0)).ToArray(); + } + } +} diff --git a/Week_01/id_86/LeetCode_905_086.py b/Week_01/id_86/LeetCode_905_086.py new file mode 100644 index 00000000..8dc2d523 --- /dev/null +++ b/Week_01/id_86/LeetCode_905_086.py @@ -0,0 +1,4 @@ + +class Solution(object): + def sortArrayByParity(self, A): + return [a for a in A if not a % 2] + [a for a in A if a % 2] diff --git a/Week_01/id_86/LeetCode_922_086.c b/Week_01/id_86/LeetCode_922_086.c new file mode 100644 index 00000000..a8a87d3a --- /dev/null +++ b/Week_01/id_86/LeetCode_922_086.c @@ -0,0 +1,21 @@ +int *MethodFor922_1(int const *A, int ASize, int *BSize) +{ + int o = 1; + int e = 0; + int *ret = (int *)malloc(sizeof(int) * (*BSize = ASize)); + + for (int i = 0; i < *BSize; ++i) + { + if (A[i] % 2 == 0) + { + ret[e] = A[i]; + e = e + 2; + } + else + { + ret[o] = A[i]; + o = o + 2; + } + } + return ret; +} \ No newline at end of file diff --git a/Week_01/id_86/LeetCode_922_086.cs b/Week_01/id_86/LeetCode_922_086.cs new file mode 100644 index 00000000..43d5b551 --- /dev/null +++ b/Week_01/id_86/LeetCode_922_086.cs @@ -0,0 +1,44 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AlgorithmTest +{ + /// + /// 922. Sort Array By Parity II + /// Given an array A of non-negative integers, half of the integers in A are odd, and half of the integers are even.Sort the array so that whenever A[i] is odd, i is odd; and whenever A[i] is even, i is even.You may return any answer array that satisfies this condition. + /// + public class LeetCode_922_086 + { + /// + /// 316ms 35.4MB + /// + /// + /// + public int[] MethodFor922_1(int[] A) + { + int n = A.Length; + int[] B = new int[n]; + + int e = 0; + int o = 1; + + for (int i = 0; i < n; i++) + { + if (A[i] % 2 == 0) + { + B[e] = A[i]; + e = e + 2; + } + else + { + B[o] = A[i]; + o = o + 2; + } + } + return B; + } + } +} diff --git a/Week_01/id_86/LeetCode_922_086.py b/Week_01/id_86/LeetCode_922_086.py new file mode 100644 index 00000000..2a239c8d --- /dev/null +++ b/Week_01/id_86/LeetCode_922_086.py @@ -0,0 +1,4 @@ +class Solution: + def sortArrayByParityII(self, A): + e, o = [a for a in A if not a % 2], [a for a in A if a % 2] + return [e.pop() if not i % 2 else o.pop() for i in range(len(A))] diff --git a/Week_01/id_87/LeetCode_24_87.java b/Week_01/id_87/LeetCode_24_87.java new file mode 100644 index 00000000..d5ec0e5e --- /dev/null +++ b/Week_01/id_87/LeetCode_24_87.java @@ -0,0 +1,26 @@ +/** +24. Swap Nodes in Pairs + +Given a linked list, swap every two adjacent nodes and return its head. + +You may not modify the values in the list's nodes, only nodes itself may be changed. + + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode(int x) { val = x; } + * } + */ +class Solution { + public ListNode swapPairs(ListNode head) { + if(head == null || head.next == null) { + return head; + }else { + ListNode newHead = head.next; + head.next = swapPairs(head.next.next); + newHead.next = head; + return newHead; + } + } +} \ No newline at end of file diff --git a/Week_01/id_87/LeetCode_33_87.java b/Week_01/id_87/LeetCode_33_87.java new file mode 100644 index 00000000..dd70cc8d --- /dev/null +++ b/Week_01/id_87/LeetCode_33_87.java @@ -0,0 +1,43 @@ + +/** +33. Search in Rotated Sorted Array + +Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. + +(i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]). + +You are given a target value to search. If found in the array return its index, otherwise return -1. + +You may assume no duplicate exists in the array. + +Your algorithm's runtime complexity must be in the order of O(log n). + + */ +class Solution { + public int search(int[] nums, int target) { + return pureBinarySearch(nums, target); + } + + /** + * inspired by idea from https://leetcode.com/problems/search-in-rotated-sorted-array/discuss/14435/Clever-idea-making-it-simple + */ + public int pureBinarySearch(int[] nums, int target) { + if(nums == null || nums.length == 0) return -1; + + int low = 0; int high = nums.length; + + while (low < high) { + int mid = (low + high)/2; + int num = (nums[mid] < nums[0]) == (target < nums[0]) ? nums[mid] : target < nums[0] ? - Integer.MAX_VALUE : Integer.MAX_VALUE; + + if(num < target) { + low = mid +1; + }else if(num > target) { + high = mid; + }else { + return mid; + } + } + return -1; + } +} diff --git a/Week_01/id_88/Leetcode_020_088.cpp b/Week_01/id_88/Leetcode_020_088.cpp new file mode 100644 index 00000000..5cf7fb3d --- /dev/null +++ b/Week_01/id_88/Leetcode_020_088.cpp @@ -0,0 +1,61 @@ +/* +* 解题思路:建立一个栈,遍历输入的符号串,当遇到'(' '{' '['符号时则进栈, +* 若出现')' '}' ']'时,则从栈中取出一个符号,如果为该右括号的左括号,则表示成功。 +* +*/ + +class Solution { +private: + vector opStack; +public: + bool isValid(string s) { + string::iterator itr = s.begin(); + for (; itr != s.end(); itr++) + { + char temp = *itr; + if (temp == '(' || temp == '{' || temp == '[') + { + opStack.push_back(temp); + } + else if (temp == ')' || temp == '}' || temp == ']') + { + if (!bMatchWithOpStack(temp)) + return false; + else + opStack.pop_back(); + } + } + //如果遍历完字符串后,opStack仍然有未匹配的符号,则表示错误。 + if(!opStack.empty()) return false; + + return true; + } + + bool bMatchWithOpStack(char op) + { + bool ret = false; + //如果opStack为空,表示没有符号与op匹配,返回错误 + if(opStack.empty()) return ret; + + char temp = opStack.back(); + + switch (op) + { + case ')': + if (temp == '(') ret = true; + break; + + case '}': + if (temp == '{') ret = true; + break; + + case ']': + if (temp == '[') ret = true; + break; + default: + break; + } + + return ret; + } +}; \ No newline at end of file diff --git a/Week_01/id_88/Leetcode_021_088.cpp b/Week_01/id_88/Leetcode_021_088.cpp new file mode 100644 index 00000000..90fca21d --- /dev/null +++ b/Week_01/id_88/Leetcode_021_088.cpp @@ -0,0 +1,76 @@ +/* +* 解题思路:建立两个临时指针指向两个链表头,开始遍历,比较当前指针的val值,取小的元素插入到新的链表中即可。 +* +* +*/ + + +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode(int x) : val(x), next(NULL) {} + * }; + */ +class Solution { +private: + //将节点取出来放到新的链表上,这样处理起来会更容易 + ListNode* newListHead; + ListNode* pNewListCur; + +public: + ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { + ListNode* pl1 = l1; + ListNode* pl2 = l2; + newListHead = NULL; + pNewListCur = NULL; + + if (l1 == NULL && l2 == NULL) + { + return NULL; + } + + if (l1 == NULL || l2 == NULL) + { + return (l1 == NULL) ? l2 : l1; + } + + while (pl1 != NULL && pl2 != NULL) + { + //把小的取出来插入到新链表中 + if (pl1->val <= pl2->val) + { + InsertToNewList(pl1); + pl1 = pl1->next; + } + else + { + InsertToNewList(pl2); + pl2 = pl2->next; + } + } + + if (pl1 == NULL) + pNewListCur->next = pl2; + else + pNewListCur->next = pl1; + + return newListHead; + + } + + void InsertToNewList(ListNode* node) + { + if (node == NULL) return; + + if (newListHead == NULL) + { + pNewListCur = newListHead = node; + } + else { + pNewListCur->next = node; + pNewListCur = pNewListCur->next; + } + } +}; \ No newline at end of file diff --git a/Week_01/id_88/Leetcode_024_088.cpp b/Week_01/id_88/Leetcode_024_088.cpp new file mode 100644 index 00000000..fe650a59 --- /dev/null +++ b/Week_01/id_88/Leetcode_024_088.cpp @@ -0,0 +1,41 @@ +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode(int x) : val(x), next(NULL) {} + * }; + */ +class Solution { +public: + ListNode* swapPairs(ListNode* head) { + ListNode* pFirst = head; + ListNode* pSecond = NULL; + ListNode* pNewListCur = NULL; + + if (head == NULL) return NULL; + + while (pFirst != NULL && pFirst->next != NULL) + { + pSecond = pFirst->next; + + pFirst->next = pSecond->next; + pSecond->next = pFirst; + + if (head == pFirst) + { + pNewListCur = head = pSecond; + } + else + { + pNewListCur->next = pSecond; + } + + pFirst = pFirst->next; + + pNewListCur = pSecond->next; + } + + return head; + } +}; \ No newline at end of file diff --git a/Week_01/id_88/Leetcode_083_088.cpp b/Week_01/id_88/Leetcode_083_088.cpp new file mode 100644 index 00000000..d6605f3f --- /dev/null +++ b/Week_01/id_88/Leetcode_083_088.cpp @@ -0,0 +1,41 @@ +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode(int x) : val(x), next(NULL) {} + * }; + */ +class Solution { +public: + ListNode* deleteDuplicates(ListNode* head) { + ListNode* pre = head; + ListNode* cur = head; + int val = 0; + + if (NULL == head) + { + return NULL; + } + + val = cur->val; + + while (cur->next != NULL) + { + cur = cur->next; + if (val == cur->val) + { + pre->next = cur->next; + delete(cur); + cur = pre; + } + else + { + val = cur->val; + pre = cur; + } + } + + return head; + } +}; \ No newline at end of file diff --git a/Week_01/id_88/Leetcode_687_088.cpp b/Week_01/id_88/Leetcode_687_088.cpp new file mode 100644 index 00000000..c90d4988 --- /dev/null +++ b/Week_01/id_88/Leetcode_687_088.cpp @@ -0,0 +1,54 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} + * }; + */ + +//#关于第687题的思路,采取自下而上的递归策略会更易理解,也就是采用后序遍历的方法。 +//另外,切勿被题目定义的函数影响了,应自行定义一个递归的函数,否则容易陷入思维死角。 +class Solution { +public: + int longestUnivaluePath(TreeNode* root) { + int max = 0; + + getMaxPath(root, max); + + return max; + } + +private: + //函数的返回值为左右子树的同值路径的边数的最大值,max参数保存的是整棵树最大的同值路径 + int getMaxPath(TreeNode* root, int& max) { + if (root == NULL) return 0; + + if (root->left == NULL && root->right == NULL) + { + return 0; + } + + //先遍历左子树,再遍历右子树,再处理root,相当于是后序遍历 + int retLeft = getMaxPath(root->left, max); + int retRight = getMaxPath(root->right, max); + + int left = 0; + if (root->left != NULL && root->val == root->left->val) + { + left = retLeft + 1; + } + + int right = 0; + if (root->right != NULL && root->val == root->right->val) + { + right = retRight + 1; + } + + //计算max的时候需要左右值相加 + max = (max > (right + left)) ? max : (right + left); + + return (right > left) ? right : left; + } +}; \ No newline at end of file diff --git a/Week_01/id_88/Leetcode_905_088.cpp b/Week_01/id_88/Leetcode_905_088.cpp new file mode 100644 index 00000000..3a544f2b --- /dev/null +++ b/Week_01/id_88/Leetcode_905_088.cpp @@ -0,0 +1,50 @@ +/* +* 解题思路:分别用head tail指向首尾两个元素,从首尾两个元素开始, +* (1)如果头元素为奇数,尾元素为偶数,则两数交换,head指向下一个元素,tail指向上一个元素 +* (2)如果头元素为奇数,尾元素为奇数,则head不动,tail指向上一个元素 +* (3)如果头元素为偶数,尾元素为偶数,则head指向下一个元素,tail不动 +* (4)如果头元素为偶数,尾元素为奇数,则head指向下一个元素,tail指向上一个元素 +* 直到head>=tail +* +*/ + +class Solution { +public: + vector sortArrayByParity(vector& A) { + int head = 0; + int tail = A.size() - 1; + int tmp = 0; + + while (head < tail) + { + if (A.at(head) % 2 != 0) + { + if (A.at(tail) % 2 == 0) + { + tmp = A.at(head); + A.at(head) = A.at(tail); + A.at(tail) = tmp; + head++; + tail--; + } + else + { + tail--; + } + } + else + { + if (A.at(tail) % 2 == 0) + { + head++; + } + else + { + head++; + tail--; + } + } + } + return A; + } +}; \ No newline at end of file diff --git a/Week_01/id_88/Leetcode_922_088.cpp b/Week_01/id_88/Leetcode_922_088.cpp new file mode 100644 index 00000000..04e9cd22 --- /dev/null +++ b/Week_01/id_88/Leetcode_922_088.cpp @@ -0,0 +1,66 @@ +/* +* 解题思路:先遍历一遍数组, +* (1)把下标index为奇数,val为偶数的元素,按照(index,val)插入到链表head1中 +* (2)把下标index为偶数,val为奇数的元素,按照(index,val)插入到链表head2中 +* 按照这两个链表的index和val进行数组值的交换即可 +* +*/ + +class Solution { + +struct ListNode { + int index; + int val; + ListNode *next; + ListNode(int i, int v) : index(i),val(v),next(NULL) {} +}; +public: + vector sortArrayByParityII(vector& A) { + int index = 0; + ListNode* head1 = NULL; + ListNode* head2 = NULL; + ListNode* pCur1 = NULL; + ListNode* pCur2 = NULL; + + for (int i = 0; i < A.size(); i++) + { + if (i % 2 == 0) + { + if (A.at(i) % 2 != 0) + { + ListNode* newNode = new ListNode(i, A.at(i)); + InsertList(&head1, newNode); + } + } + else + { + if (A.at(i) % 2 == 0) + { + ListNode* newNode = new ListNode(i, A.at(i)); + InsertList(&head2, newNode); + } + } + } + + pCur1 = head1; + pCur2 = head2; + + while (pCur1 != NULL && pCur2 != NULL) + { + A.at(pCur1->index) = pCur2->val; + A.at(pCur2->index) = pCur1->val; + pCur1 = pCur1->next; + pCur2 = pCur2->next; + } + + return A; + + } + +private: + void InsertList(ListNode** head, ListNode* node) + { + node->next = *head; + *head = node; + } +}; \ No newline at end of file diff --git a/Week_01/id_88/NOTE.md b/Week_01/id_88/NOTE.md index c684e62f..c7b04df0 100644 --- a/Week_01/id_88/NOTE.md +++ b/Week_01/id_88/NOTE.md @@ -1 +1,4 @@ -# 学习笔记 \ No newline at end of file +# 学习笔记 + +#关于第687题的思路,采取自下而上的递归策略会更易理解,也就是采用后序遍历的方法。另外,切勿被题目定义的函数影响了,应自行定义一个递归的函数,否则容易陷入思维死角。 + diff --git a/Week_01/id_9/LeetCode_687_9.cs b/Week_01/id_9/LeetCode_687_9.cs new file mode 100644 index 00000000..fac95331 --- /dev/null +++ b/Week_01/id_9/LeetCode_687_9.cs @@ -0,0 +1,64 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProblemSolutions +{ + public class Problem687 : IProblem + { + public class TreeNode + { + public int val; + public TreeNode left; + public TreeNode right; + public TreeNode(int x) { val = x; } + } + + public void RunProblem() + { + throw new NotImplementedException(); + } + + public int LongestUnivaluePath(TreeNode root) + { + /* + * 树的遍历,使用的是“根、左、右”的方式; + * 遍历过程中,有两个职责: + * 1.左右节点和自己同值,那么加起来和最大长度比较一下; + * 2.若节点的值,与父节点的值相同,那么就把左右子树最大的值,再加上自己的值,返回给父节点; + * + * 时间复杂度:就是把树遍历了一遍,顺便做了比较,所以是O(n); + * 空间复杂度:O(1); + */ + + if (root == null) return 0; + TreeSearch(root, root.val); + return maxL; + } + + private int maxL = int.MinValue; + + /// + /// 二叉树遍历求值 + /// + /// 子节点 + /// 父节点的值 + /// 与父节点值相同的节点个数 + private int TreeSearch(TreeNode sonNode, int val) + { + if (sonNode == null) return 0; + + //左右节点和自己同值,那么加起来和最大长度比较一下; + var leftCount = TreeSearch(sonNode.left, sonNode.val); + var rightCount = TreeSearch(sonNode.right, sonNode.val); + maxL = Math.Max(leftCount + rightCount, maxL); + + //若节点的值,与父节点的值相同,那么就把左右子树最大的值,再加上自己的值,返回给父节点; + if (sonNode.val == val) return Math.Max(leftCount, rightCount) + 1; + + return 0; + } + } +} diff --git a/Week_01/id_9/LeetCode_83_9.cs b/Week_01/id_9/LeetCode_83_9.cs new file mode 100644 index 00000000..0ebbfe8a --- /dev/null +++ b/Week_01/id_9/LeetCode_83_9.cs @@ -0,0 +1,48 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ProblemSolutions +{ + public class Problem083 : IProblem + { + public class ListNode + { + public int val; + public ListNode next; + public ListNode(int x) { val = x; } + } + + public void RunProblem() + { + throw new NotImplementedException(); + } + + public ListNode DeleteDuplicates(ListNode head) + { + /* + * 当前结点,是在遍历的过程中做检测,是该移动一步,还是该排除掉一个重复的情况 + * 单链表基本操作的数量程度 + * 时间复杂度:O(n),只是一次单链表的遍历 + * 空间复杂度:O(1),使用的存储空间是固定的 + */ + + ListNode cur = head; + + while(cur != null && cur.next != null) + { + if(cur.val != cur.next.val) + { + cur = cur.next; + continue; + } + + cur.next = cur.next.next; + } + + return head; + } + } +} diff --git a/Week_01/id_9/NOTE.md b/Week_01/id_9/NOTE.md index c684e62f..109d61f7 100644 --- a/Week_01/id_9/NOTE.md +++ b/Week_01/id_9/NOTE.md @@ -1 +1,4 @@ -# 学习笔记 \ No newline at end of file +# 学习笔记 +1. 算法的知识点有很多,要掌握他们,最好的办法是各个击破,也就是说针对每个知识点,每次做大量的题,总结和体会;最怕的是,每个知识点浅尝辄止,初学的时候,每天都做跨多个知识点的题目; +2. 算法的难易,考验的是对这个知识点的掌握程度,体会理解越深越简单,本次做了一个树的题目,题目难易度是“简单”,可我却觉得异常困难,原因其实是,树的题目,我基本没练习过,基础不牢导致; +3. 以上是本周做题总结出来的,现在打算每周单独练习各个知识点,知道掌握和熟悉; \ No newline at end of file diff --git a/Week_01/id_90/LeetCode_20_90.java b/Week_01/id_90/LeetCode_20_90.java new file mode 100644 index 00000000..15ec53d8 --- /dev/null +++ b/Week_01/id_90/LeetCode_20_90.java @@ -0,0 +1,25 @@ +/** + * + */ +class LeetCode_20_95 { + public boolean isValid(String s) { + //建立栈对象,用于char类型入栈 + Stack stack = new Stack(); + + //遍历字符串 + for(char c : s.toCharArray()){ + if(c == '('){ + stack.push(')');//压栈 + }else if(c == '['){ + stack.push(']'); + }else if(c == '{'){ + stack.push('}'); + }else if(stack.isEmpty() || stack.pop()!=c){//stack.pop()!=c + return false; + } + + } + return true; + + } +} \ No newline at end of file diff --git a/Week_01/id_90/LeetCode_83_90.java b/Week_01/id_90/LeetCode_83_90.java new file mode 100644 index 00000000..d7ed74d6 --- /dev/null +++ b/Week_01/id_90/LeetCode_83_90.java @@ -0,0 +1,31 @@ +/** + * + */ +public class LeetCode_83_95 {//链表第一题 + public static ListNode deleteDuplicates(ListNode head) { + + //首先判断空 + if(head == null || head.next == null){ + return head; + } + + ListNode node = head;//相当于指针 + while(node.next != null){ + if(node.val == node.next.val){ + node.next = node.next.next; + }else{ + node = node.next;//循环增加的条件 + } + } + return head; + } + +} + +class ListNode{ + int val;//实际的值 + ListNode next;//下一节点 + public ListNode(int x){ + val = x; + } +} \ No newline at end of file diff --git a/Week_01/id_90/NOTE.md b/Week_01/id_90/NOTE.md index c684e62f..5373e695 100644 --- a/Week_01/id_90/NOTE.md +++ b/Week_01/id_90/NOTE.md @@ -1 +1,3 @@ -# 学习笔记 \ No newline at end of file +# 学习笔记 + +基础太差,开始看算法图解。。。 \ No newline at end of file diff --git a/Week_01/id_91/LeetCode_242_091.java b/Week_01/id_91/LeetCode_242_091.java new file mode 100644 index 00000000..c23a0cad --- /dev/null +++ b/Week_01/id_91/LeetCode_242_091.java @@ -0,0 +1,28 @@ +/** + * 有效的字母异位词 + * 给定两个字符串 s 和 t ,编写一个函数来判断 t 是否是 s 的一个字母异位词。 + * https://leetcode-cn.com/problems/valid-anagram/ + */ +class Solution { + public boolean isAnagram(String s, String t) { + + if(s==null||t==null){ + return false; + } + if(s.length()!=t.length()){ + return false; + } + + int[] counter = new int[26]; + for (int i = 0; i < s.length(); i++) { + counter[s.charAt(i) - 'a']++; + counter[t.charAt(i) - 'a']--; + } + for (int count : counter) { + if (count != 0) { + return false; + } + } + return true; + } +} \ No newline at end of file diff --git a/Week_01/id_91/LeetCode_441_091.java b/Week_01/id_91/LeetCode_441_091.java new file mode 100644 index 00000000..02f98a52 --- /dev/null +++ b/Week_01/id_91/LeetCode_441_091.java @@ -0,0 +1,30 @@ +/** + * 你总共有 n 枚硬币,你需要将它们摆成一个阶梯形状,第 k 行就必须正好有 k 枚硬币。 + * + * 给定一个数字 n,找出可形成完整阶梯行的总行数。 + * + * n 是一个非负整数,并且在32位有符号整型的范围内。 + * https://leetcode-cn.com/problems/arranging-coins/ + * @author jidw + */ +class Solution { + public int arrangeCoins(int n) { + if(n == 1){ + return 1; + } + long nlong = (long) n; + + long start = 0, end = nlong; + while(start + 1 < end){ + long mid = start + (end - start) / 2; + + if(mid*(mid+1) <= 2*nlong){ + start = mid; + } + else{ + end = mid; + } + } + return (int)(start); + } +} \ No newline at end of file diff --git a/Week_01/id_94/LeetCode_83_094.py.py b/Week_01/id_94/LeetCode_83_094.py.py new file mode 100644 index 00000000..3572c1d4 --- /dev/null +++ b/Week_01/id_94/LeetCode_83_094.py.py @@ -0,0 +1,27 @@ +# Definition for singly-linked list. +class ListNode(object): + + def __init__(self, x): + self.val = x + self.next = None + + +class Solution(object): + + def deleteDuplicates(self, head): + + current = head + if current is None: + return head + while current.next is not None: + if current.val == current.next.val: + if current.next.next is not None: + current.next = current.next.next + # current = current.next + else: + current.next = None + else: + current = current.next + return head + + diff --git a/Week_01/id_94/LeetCode_905_094.py b/Week_01/id_94/LeetCode_905_094.py new file mode 100644 index 00000000..584e5359 --- /dev/null +++ b/Week_01/id_94/LeetCode_905_094.py @@ -0,0 +1,32 @@ +class Solution(object): + def sortArrayByParity(self, A): + left = 0 + right = len(A)-1 + middle = int((right+left)/2) + print ("中间值",middle) + while(left topKFrequent(String[] words, int k) { + + Map map = new HashMap<>(); + + int len = words.length; + for (int i = 0; i < len; i ++) { + String word = words[i]; + int value = map.getOrDefault(word, 0) + 1; + map.put(word, value); + } + + List> entrys = new ArrayList>(map.entrySet()); + + Collections.sort(entrys, new Comparator>() { + @Override + public int compare(Map.Entry o1, Map.Entry o2) { + if (o1.getValue() > o2.getValue()){ + return -1; + }else if (o1.getValue() < o2.getValue()) { + return 1; + }else { + return o1.getKey().compareTo(o2.getKey()); + } + } + }); + + List result = new ArrayList<>(); + for (int i=0; i < k; i ++) { + result.add(entrys.get(i).getKey()); + } + + return result; + } +} \ No newline at end of file diff --git a/Week_02/id_1/NOTE.md b/Week_02/id_1/NOTE.md index c684e62f..fe3a79fc 100644 --- a/Week_02/id_1/NOTE.md +++ b/Week_02/id_1/NOTE.md @@ -1 +1,97 @@ -# 学习笔记 \ No newline at end of file +# 第二周总结-LeetCode236 做题简记与资源分享 + + +本周只做了两道题目,主要是被 236 题给难住了,参考了 discuss 中的答案才想清楚,这里整理一波该题的做题思路吧。 + +```Java +class Solution { + public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { + + // 1. 递归终止条件:到达叶节点或者目标节点 + if(root == null || root == p || root == q) { + return root; + } + + + // 2. 递归公式:当前节点是否为 p、q 两个节点的祖先节点 + TreeNode left = lowestCommonAncestor(root.left, p, q); + TreeNode right = lowestCommonAncestor(root.right, p, q); + + // 3. 基于递归结果求解 + if (left == null) { + return right; + } + + if (right == null) { + return left; + } + + return root; + } +} +``` + +题目要求是求 p、q 节点的最近的祖先节点,这里有两种情况 + +- 1. p、q 有共同的祖先节点,那么返回结果就是最低的祖先节点 + +![](https://github.com/zouyingjie/arts/blob/master/image/algorithm01.png) + +- 2. 一个节点为另一个节点的祖先节点,那么返回的就是 p、q 中的那个祖先节点 + +![](https://github.com/zouyingjie/arts/blob/master/image/algorithm03.png) + + +对于树相关的题目,一个很重要的做题原则就是: + +> 只关注一个节点 + +回到 第 236 题,如果确定一个节点是否为 p、q 两个节点的祖先节点,判断依据就是 + +- 其左右子树中包含两个节点 + +那么我们要做的就是查看其左子树、右子树是否包含 p、q 两个节点。同样对于左右子节点,依然是采用相同的逻辑判断,这里完全符合递归的求解方式:大问题拆分为逻辑相同的子问题。代码如下: + +``` +TreeNode left = lowestCommonAncestor(root.left, p, q); +TreeNode right = lowestCommonAncestor(root.right, p, q); +``` +对于一个节点计算完成后,我们得到了其左右子树包含 p、q 节点的结果,此时再基于上面提到的两种情况进行结果返回 + +***拥有共同祖先节点*** + +该种其结果一定是左右子树都可能查找到对应的节点,因此只要某个节点的查找结果满足 + +> left != null && right !=null + +就说明该节点就是 p、q 的共同祖先节点。 + +***一个节点为另一个节点的祖先节点*** + +此时,计算的结果会如图所示: + +![](https://github.com/zouyingjie/arts/blob/master/image/algorithms04.png) + +x 为 y 的节点父节点, x 的父节点在计算时,left 为空,right 则返回了 x 节点自身。因此对于这种情况,当 left 或 right 有一个为 null 一个不为 null 时, +不为 null 的节点即为共同祖先节点。 + + +采用递归的解法,最快的情况下每个节点都要遍历一遍,时间复杂度为 O(N),空间上只有节点的空间占用,因此空间复杂度也为 O(N)。 + +严格来说并不是一道很难做的题目,但是自己在做题时动不动就想复杂了,虽然捋清楚了两种情况,但是在实现递归代码时没想明白,重要的还是要聚焦于一个节点上,对于树相关的题目解析,一般都是一个个节点上的重复逻辑计算,只要把一个节点上的逻辑搞明白,就可以采用递归的方式求解了,递归方面还是很薄弱,需要进一步加强练习。 + +***资源分享*** + +#### 1.Youtube 的两个频道 + +- [Vivekanand Khyade - Algorithm Every Day](https://www.youtube.com/channel/UCx-kFfzekMbhODaBss-ZnsA):一位印度小哥的算法讲解视频,口音有浓重的咖喱味,但理解起来也不算很难,耐心的多听几遍基本可以听懂,既可以学算法,也可以练听力。 +- [Back To Back SWE](https://www.youtube.com/channel/UCmJz2DV1a3yfgrR7GqRtUUA):这是做第 236 题时搜到了这个频道的讲解视频,发音更标准一些,本次题目思路的整理主要是参考了频道里面的一个讲解视频。 + +#### 2. 《算法》配套课程 + +皓叔在专栏中也推荐过 [算法](https://book.douban.com/subject/10432347/)这本书,其实本书的作者 Robert Sedgewick 还针对书籍出了一个配套课程发布在了 [Coursera](https://www.coursera.org/) 上。 + +- [Algorithms-Part1](https://www.coursera.org/learn/algorithms-part1):第一部分介绍了并查集、栈、队列、链表、排序等基础算法 +- [Algorithms-Part2](https://www.coursera.org/learn/algorithms-part2):第二部分相对较难,介绍了图、最短路径、字符串相关的算法。 + +看书的同学有兴趣的话可以参照课程进行辅助学习。 \ No newline at end of file diff --git a/Week_02/id_100/LeetCode_242_100.java b/Week_02/id_100/LeetCode_242_100.java new file mode 100644 index 00000000..2c831502 --- /dev/null +++ b/Week_02/id_100/LeetCode_242_100.java @@ -0,0 +1,24 @@ +class Solution { + public boolean isAnagram(String s, String t) { + boolean result = false; + if (s != null && t != null) { + if (s.length() == t.length()) { + char[] s_char = s.toCharArray(); + char[] t_char = t.toCharArray(); + int r = 0; + for (int i = 0; i < s_char.length; i++) { + for (int j = 0; j < t_char.length; j++) { + if (s_char[i] == t_char[j]) { + r++; + break; + } + } + } + if (r == s.length() && r == t.length()) { + result = true; + } + } + } + return result; + } +} diff --git a/Week_02/id_100/LeetCode_671_100.java b/Week_02/id_100/LeetCode_671_100.java new file mode 100644 index 00000000..0fe845ce --- /dev/null +++ b/Week_02/id_100/LeetCode_671_100.java @@ -0,0 +1,34 @@ +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +class Solution { + public int findSecondMinimumValue(TreeNode root) { + return traversal(root, root.val); + } + + private static int traversal(TreeNode root, int rootVal) { + if (root == null) { + return -1; + } + if (root.val > rootVal) { + return root.val; + } + + int l = traversal(root.left, rootVal); // 遍历左节点值是否有大于根节点的值 3 + System.out.println("left ----> " + l); + int r = traversal(root.right, rootVal); // 遍历右节点值是否有大于根节点的值 7 + System.out.println("right --->" + r); + // 如果左右节点都比跟节点大的话,取最小的 + if (l >= 0 && r >= 0) { + return Math.min(l, r); + } + // 否则取最大的 + return Math.max(l, r); + } +} diff --git a/Week_02/id_100/LeetCode_783_100.java b/Week_02/id_100/LeetCode_783_100.java new file mode 100644 index 00000000..24b7f9b5 --- /dev/null +++ b/Week_02/id_100/LeetCode_783_100.java @@ -0,0 +1,33 @@ +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +class Solution { + int result = 101; + public int minDiffInBST(TreeNode root) { + if (root != null) { + if (root.left != null) { + int i = Math.abs(root.val - root.left.val); + result = i < result ? i : result; + } + if (root.right != null) { + int i = Math.abs(root.val - root.right.val); + result = i < result ? i : result; + } + int l = minDiffInBST(root.left); + int r = minDiffInBST(root.right); + if (l <= r) { + result = l; + } else { + return r; + } + result = l <= r ? l : r; + } + return result; + } +} diff --git a/Week_02/id_102/leetcode_236_102.cpp b/Week_02/id_102/leetcode_236_102.cpp new file mode 100644 index 00000000..d5ce45f6 --- /dev/null +++ b/Week_02/id_102/leetcode_236_102.cpp @@ -0,0 +1,39 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} + * }; + * Link: https://leetcode-cn.com/problems/all-nodes-distance-k-in-binary-tree/ + * 3 + * + * 5 1 + * + * 6 2 0 8 + * + * 7 4 + */ + +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 && right != NULL) { + return root; + } + + if (left != NULL) { + return left; + } + + return right; + } +}; \ No newline at end of file diff --git a/Week_02/id_102/leetcode_671_102.cpp b/Week_02/id_102/leetcode_671_102.cpp new file mode 100644 index 00000000..34259516 --- /dev/null +++ b/Week_02/id_102/leetcode_671_102.cpp @@ -0,0 +1,37 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} + * }; + * Link: https://leetcode-cn.com/problems/second-minimum-node-in-a-binary-tree/comments/ + */ +class Solution { + long secondMinVal = LONG_MAX; + bool isRoot = true; + int rootVal; + +public: + int findSecondMinimumValue(TreeNode* root) { + if (root == NULL) { + return -1; + } + + if (isRoot) { + isRoot = false; + rootVal = root->val; + } + + /* 寻找比root value大,但是比secondMinVal小的值 ß*/ + if ((long)root->val > rootVal && (long)root->val < secondMinVal) { + secondMinVal = (long)root->val; + } + + findSecondMinimumValue(root->left); + findSecondMinimumValue(root->right); + + return secondMinVal != LONG_MAX ? secondMinVal : -1; + } +}; \ No newline at end of file diff --git a/Week_02/id_102/leetcode_783_102.cpp b/Week_02/id_102/leetcode_783_102.cpp new file mode 100644 index 00000000..a14365c5 --- /dev/null +++ b/Week_02/id_102/leetcode_783_102.cpp @@ -0,0 +1,43 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} + * }; + * Link: https://leetcode-cn.com/problems/minimum-distance-between-bst-nodes/ + */ +class Solution { + int minDiff = INT_MAX; + TreeNode *prev; +public: + int minDiffInBST(TreeNode* root) { + int res = INT_MAX; + inOrderBST(root); + return minDiff; + } + +private: + void inOrderBST(TreeNode* root) { + if (NULL == root) { + return; + } + + /* 深度优先遍历 中序遍历 */ + inOrderBST(root->left); + if (prev != NULL) { + minDiff = getmin(minDiff, root->val - prev->val); + } + + prev = root; + inOrderBST(root->right); + + return; + } + +private: + int getmin(int value1, int value2) { + return (value1 > value2 ? value2: value1); + } +}; diff --git a/Week_02/id_103/.idea/workspace.xml b/Week_02/id_103/.idea/workspace.xml new file mode 100644 index 00000000..828c0b82 --- /dev/null +++ b/Week_02/id_103/.idea/workspace.xml @@ -0,0 +1,213 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +