diff --git a/.gitignore b/.gitignore index 90e76642..7cabbc1b 100644 --- a/.gitignore +++ b/.gitignore @@ -20,4 +20,5 @@ out/ # should NOT be excluded as they contain compiler settings and other important # information for Eclipse / Flash Builder. */target/ -*.class \ No newline at end of file +*.class +/notes/target/ diff --git a/leetcode/README_EN.md b/leetcode/README_EN.md deleted file mode 100644 index c2aac0cc..00000000 --- a/leetcode/README_EN.md +++ /dev/null @@ -1,190 +0,0 @@ -
- - - -## Introduction - -Complete solutions to [LeetCode](https://leetcode-cn.com/problemset/all/), [LCOF](https://leetcode-cn.com/problemset/lcof/) and [LCCI](https://leetcode-cn.com/problemset/lcci/) problems, updated daily. - -[中文文档](/README.md) - -## Sites - -- Netlify: https://lc.netlify.app -- Gitee Pages: https://doocs.gitee.io/leetcode -- GitHub Pages: https://doocs.github.io/leetcode - -## Solutions - -- [LeetCode](/solution/README_EN.md) -- [LCOF: _Coding Interviews, 2nd Edition_](/lcof/README_EN.md) -- [LCCI: _Cracking the Coding Interview, 6th Edition_](/lcci/README_EN.md) - -## Basic Algorithms - -### Sorting - -- [Bubble Sort](/basic/sorting/BubbleSort/README.md) -- [Insertion Sort](/basic/sorting/InsertionSort/README.md) -- [Selection Sort](/basic/sorting/SelectionSort/README.md) -- [Merge Sort](/basic/sorting/MergeSort/README.md) -- [Quick Sort](/basic/sorting/QuickSort/README.md) - -### Searching - -- [Binary Search](/basic/searching/BinarySearch/README.md) -- [Binary Search II](/basic/searching/BinarySearch-II/README.md) - -## High Frequency Interview Questions - -### Arrays - -- [Remove Duplicates from Sorted Array](/solution/0000-0099/0026.Remove%20Duplicates%20from%20Sorted%20Array/README_EN.md) -- [Remove Element](/solution/0000-0099/0027.Remove%20Element/README_EN.md) -- [Move Zeroes](/solution/0200-0299/0283.Move%20Zeroes/README_EN.md) -- [Rotate Array](/solution/0100-0199/0189.Rotate%20Array/README_EN.md) -- [Spiral Matrix](/solution/0000-0099/0054.Spiral%20Matrix/README_EN.md) -- [Two Sum](/solution/0000-0099/0001.Two%20Sum/README_EN.md) -- [3Sum](/solution/0000-0099/0015.3Sum/README_EN.md) -- [4Sum](/solution/0000-0099/0018.4Sum/README_EN.md) -- [Merge Sorted Array](/solution/0000-0099/0088.Merge%20Sorted%20Array/README_EN.md) -- [Find Minimum in Rotated Sorted Array](/solution/0100-0199/0153.Find%20Minimum%20in%20Rotated%20Sorted%20Array/README_EN.md) -- [Find Minimum in Rotated Sorted Array II](/solution/0100-0199/0154.Find%20Minimum%20in%20Rotated%20Sorted%20Array%20II/README_EN.md) -- [Product of Array Except Self](/solution/0200-0299/0238.Product%20of%20Array%20Except%20Self/README_EN.md) - -### Strings - -- [Reverse Vowels of a String](/solution/0300-0399/0345.Reverse%20Vowels%20of%20a%20String/README_EN.md) -- [String to Integer (atoi)](/solution/0000-0099/0008.String%20to%20Integer%20%28atoi%29/README_EN.md) -- [Ransom Note](/solution/0300-0399/0383.Ransom%20Note/README_EN.md) - -### Linked List - -- [Add Two Numbers](/solution/0000-0099/0002.Add%20Two%20Numbers/README_EN.md) -- [Delete Node in a Linked List](/solution/0200-0299/0237.Delete%20Node%20in%20a%20Linked%20List/README_EN.md) -- [Remove Linked List Elements](/solution/0200-0299/0203.Remove%20Linked%20List%20Elements/README_EN.md) -- [Kth Node From End of List](/lcci/02.02.Kth%20Node%20From%20End%20of%20List/README_EN.md) -- [Swap Nodes in Pairs](/solution/0000-0099/0024.Swap%20Nodes%20in%20Pairs/README_EN.md) -- [Merge Two Sorted Lists](/solution/0000-0099/0021.Merge%20Two%20Sorted%20Lists/README_EN.md) -- [Merge k Sorted Lists](/solution/0000-0099/0023.Merge%20k%20Sorted%20Lists/README_EN.md) -- [Insertion Sort List](/solution/0100-0199/0147.Insertion%20Sort%20List/README_EN.md) -- [Sort List](/solution/0100-0199/0148.Sort%20List/README_EN.md) -- [Reverse Linked List](/solution/0200-0299/0206.Reverse%20Linked%20List/README_EN.md) -- [Reverse Linked List II](/solution/0000-0099/0092.Reverse%20Linked%20List%20II/README_EN.md) -- [Reorder List](/solution/0100-0199/0143.Reorder%20List/README_EN.md) -- [Rotate List](/solution/0000-0099/0061.Rotate%20List/README_EN.md) -- [Palindrome Linked List](/solution/0200-0299/0234.Palindrome%20Linked%20List/README_EN.md) -- [Intersection of Two Linked Lists](/solution/0100-0199/0160.Intersection%20of%20Two%20Linked%20Lists/README_EN.md) -- [Odd Even Linked List](/solution/0300-0399/0328.Odd%20Even%20Linked%20List/README_EN.md) -- [Linked List Cycle](/solution/0100-0199/0141.Linked%20List%20Cycle/README_EN.md) -- [Linked List Cycle II](/solution/0100-0199/0142.Linked%20List%20Cycle%20II/README_EN.md) -- [Design Linked List](/solution/0700-0799/0707.Design%20Linked%20List/README_EN.md) - -### Binary Tree - -- [Symmetric Tree](/solution/0100-0199/0101.Symmetric%20Tree/README_EN.md) -- [Invert Binary Tree](/solution/0200-0299/0226.Invert%20Binary%20Tree/README_EN.md) -- [Binary Tree Level Order Traversal](/solution/0100-0199/0102.Binary%20Tree%20Level%20Order%20Traversal/README_EN.md) -- [Binary Tree Level Order Traversal II](/solution/0100-0199/0107.Binary%20Tree%20Level%20Order%20Traversal%20II/README_EN.md) -- [Maximum Depth of Binary Tree](/solution/0100-0199/0104.Maximum%20Depth%20of%20Binary%20Tree/README_EN.md) -- [Minimum Depth of Binary Tree](/solution/0100-0199/0111.Minimum%20Depth%20of%20Binary%20Tree/README_EN.md) -- [Binary Tree Paths](/solution/0200-0299/0257.Binary%20Tree%20Paths/README_EN.md) -- [Path Sum](/solution/0100-0199/0112.Path%20Sum/README_EN.md) -- [Path Sum II](/solution/0100-0199/0113.Path%20Sum%20II/README_EN.md) -- [Construct Binary Tree from Preorder and Inorder Traversal](/solution/0100-0199/0105.Construct%20Binary%20Tree%20from%20Preorder%20and%20Inorder%20Traversal/README_EN.md) -- [Construct Binary Tree from Inorder and Postorder Traversal](/solution/0100-0199/0106.Construct%20Binary%20Tree%20from%20Inorder%20and%20Postorder%20Traversal/README_EN.md) -- [Lowest Common Ancestor of a Binary Tree](/solution/0200-0299/0236.Lowest%20Common%20Ancestor%20of%20a%20Binary%20Tree/README_EN.md) -- [Lowest Common Ancestor of a Binary Search Tree](/solution/0200-0299/0235.Lowest%20Common%20Ancestor%20of%20a%20Binary%20Search%20Tree/README_EN.md) -- [BiNode](/lcci/17.12.BiNode/README_EN.md) -- [Convert Binary Search Tree to Sorted Doubly Linked List](/solution/0400-0499/0426.Convert%20Binary%20Search%20Tree%20to%20Sorted%20Doubly%20Linked%20List/README_EN.md) - -### Math - -- [Single Number](/solution/0100-0199/0136.Single%20Number/README_EN.md) -- [Single Number II](/solution/0100-0199/0137.Single%20Number%20II/README_EN.md) -- [Single Number III](/solution/0200-0299/0260.Single%20Number%20III/README_EN.md) -- [Set Mismatch](/solution/0600-0699/0645.Set%20Mismatch/README_EN.md) -- [Count Primes](/solution/0200-0299/0204.Count%20Primes/README_EN.md) -- [Missing Number](/solution/0200-0299/0268.Missing%20Number/README_EN.md) - -### Stack & Queue - -- [Valid Parentheses](/solution/0000-0099/0020.Valid%20Parentheses/README_EN.md) -- [Min Stack](/solution/0100-0199/0155.Min%20Stack/README_EN.md) -- [Implement Queue using Stacks](/solution/0200-0299/0232.Implement%20Queue%20using%20Stacks/README_EN.md) -- [Implement Stack using Queues](/solution/0200-0299/0225.Implement%20Stack%20using%20Queues/README_EN.md) -- [Evaluate Reverse Polish Notation](/solution/0100-0199/0150.Evaluate%20Reverse%20Polish%20Notation/README_EN.md) -- [Number of Recent Calls](/solution/0900-0999/0933.Number%20of%20Recent%20Calls/README_EN.md) -- [Daily Temperatures](/solution/0700-0799/0739.Daily%20Temperatures/README_EN.md) - -### Dynamic Programming - -- [Maximum Subarray](/solution/0000-0099/0053.Maximum%20Subarray/README_EN.md) -- [Maximum Product Subarray](/solution/0100-0199/0152.Maximum%20Product%20Subarray/README_EN.md) -- [House Robber](/solution/0100-0199/0198.House%20Robber/README_EN.md) -- [House Robber II](/solution/0200-0299/0213.House%20Robber%20II/README_EN.md) -- [Longest Increasing Subsequence](/solution/0300-0399/0300.Longest%20Increasing%20Subsequence/README_EN.md) -- [Russian Doll Envelopes](/solution/0300-0399/0354.Russian%20Doll%20Envelopes/README_EN.md) - -### Misc - -- [Combine Two Tables](/solution/0100-0199/0175.Combine%20Two%20Tables/README_EN.md) -- [Second Highest Salary](/solution/0100-0199/0176.Second%20Highest%20Salary/README_EN.md) -- [Nth Highest Salary](/solution/0100-0199/0177.Nth%20Highest%20Salary/README_EN.md) -- [Rank Scores](/solution/0100-0199/0178.Rank%20Scores/README_EN.md) - -## Maintainer - -[Yang Libin](https://github.com/yanglbme): Creator of [@Doocs](https://github.com/doocs) technical community; member of [@TheAlgorithms](https://github.com/TheAlgorithms) organization. - -## Contributions - -I'm looking for long-term contributors/partners to this repo! Send me [PRs](https://github.com/doocs/leetcode/pulls) if you're interested! See the following: - -1. Fork [this repository](https://github.com/doocs/leetcode) to your own GitHub account and then clone it to your local machine. -1. Make some changes to your leetcode repository, then add, commit and push the changes to your remote GitHub repository. -1. Submit a pull request with your changes! -1. See [CONTRIBUTING](https://github.com/doocs/.github/blob/main/CONTRIBUTING.md) or [GitHub Help](https://help.github.com/en) for more details. - - - -You can also contribute to [doocs/leetcode](https://github.com/doocs/leetcode) using [Gitpod.io](https://www.gitpod.io), a free online dev environment with a single click. - -[](https://gitpod.io/#https://github.com/doocs/leetcode) - -## Contributors - -This project exists thanks to all the people who contribute. - -Implement an algorithm to determine if a string has all unique characters. What if you cannot use additional data structures?
- -Example 1:
- -
-
-Input: s
= "leetcode"
-
-Output: false
-
-
-
-Example 2:
- -
-
-Input: s
= "abc"
-
-Output: true
-
-
-
-Note:
- -0 <= len(s) <= 100
Given two strings,write a method to decide if one is a permutation of the other.
- -Example 1:
- -- -Input:- -s1
= "abc",s2
= "bca" - -Output: true - -
Example 2:
- -- -Input:- -s1
= "abc",s2
= "bad" - -Output: false - -
Note:
-0 <= len(s1) <= 100
0 <= len(s2) <= 100
Write a method to replace all spaces in a string with '%20'. You may assume that the string has sufficient space at the end to hold the additional characters,and that you are given the "true" length of the string. (Note: If implementing in Java,please use a character array so that you can perform this operation in place.)
- -Example 1:
- -- -Input: "Mr John Smith ", 13 - -Output: "Mr%20John%20Smith" - -Explanation: - -The missing numbers are [5,6,8,...], hence the third missing number is 8. - -- -
Example 2:
- -- -Input: " ", 5 - -Output: "%20%20%20%20%20" - -- -
- -
Note:
- -0 <= S.length <= 500000
Given a string, write a function to check if it is a permutation of a palin drome. A palindrome is a word or phrase that is the same forwards and backwards. A permutation is a rearrangement of letters. The palindrome does not need to be limited to just dictionary words.
- -- -
Example1:
- -- -Input: "tactcoa" - -Output: true(permutations: "tacocat"、"atcocta", etc.) - -- -## Solutions - - - -### **Python3** - -```python -class Solution: - def canPermutePalindrome(self, s: str) -> bool: - if s is None or len(s) < 2: - return True - cache = {} - for ch in s: - cache[ch] = 1 if cache.get(ch) is None else cache[ch] + 1 - cnt = 0 - for k, v in cache.items(): - if (v & 1) == 1: - cnt += 1 - if cnt > 1: - return False - return cnt <= 1 -``` - -### **Java** - -```java -package src.main.java; -import java.util.*; - -public class Solution { - public boolean canPermutePalindrome(String s) { - if (s == null || s.length() < 2) { - return true; - } - char[] chars = s.toCharArray(); - Map
There are three types of edits that can be performed on strings: insert a character, remove a character, or replace a character. Given two strings, write a function to check if they are one edit (or zero edits) away.
- -Example 1:
- -- -Input: - -first = "pale" - -second = "ple" - -Output: True - -- -
Example 2:
- -- -Input: - -first = "pales" - -second = "pal" - -Output: False - -- -## Solutions - - - -### **Python3** - -```python -class Solution: - def oneEditAway(self, first: str, second: str) -> bool: - n1, n2 = len(first), len(second) - if abs(n1 - n2) > 1: - return False - if n1 + n2 <= 2: - return True - if first[0] != second[0]: - if n1 == n2: - return first[1:] == second[1:] - else: - return first[1:] == second or second[1:] == first - else: - return self.oneEditAway(first[1:], second[1:]) -``` - -### **Java** - -```java -package src.main.java; -import java.util.*; - -public class Solution { - public boolean oneEditAway(String first, String second) { - int n1 = first.length(), n2 = second.length(); - int differ = Math.abs(n1 - n2); - if (differ > 1) { - return false; - } - if (n1 + n2 <= 2) { - return true; - } - if (first.charAt(0) != second.charAt(0)) { - if (n1 == n2) { - return first.substring(1).equals(second.substring(1)); - } else { - return first.substring(1).equals(second) || second.substring(1).equals(first); - } - } else { - return oneEditAway(first.substring(1), second.substring(1)); - } - } -} -``` - -### **...** - -``` - -``` - - diff --git a/leetcode/lcci/src.main/java/01.05.One Away/Solution.py b/leetcode/lcci/src.main/java/01.05.One Away/Solution.py deleted file mode 100644 index b801678b..00000000 --- a/leetcode/lcci/src.main/java/01.05.One Away/Solution.py +++ /dev/null @@ -1,14 +0,0 @@ -class Solution: - def oneEditAway(self, first: str, second: str) -> bool: - n1, n2 = len(first), len(second) - if abs(n1 - n2) > 1: - return False - if n1 + n2 <= 2: - return True - if first[0] != second[0]: - if n1 == n2: - return first[1:] == second[1:] - else: - return first[1:] == second or second[1:] == first - else: - return self.oneEditAway(first[1:], second[1:]) \ No newline at end of file diff --git a/leetcode/lcci/src.main/java/01.06.Compress String/README_EN.md b/leetcode/lcci/src.main/java/01.06.Compress String/README_EN.md deleted file mode 100644 index 385f9249..00000000 --- a/leetcode/lcci/src.main/java/01.06.Compress String/README_EN.md +++ /dev/null @@ -1,93 +0,0 @@ -# [01.06. Compress String](https://leetcode-cn.com/problems/compress-string-lcci) - -[中文文档](/lcci/01.06.Compress%20String/README.md) - -## Description - -
Implement a method to perform basic string compression using the counts of repeated characters. For example, the string aabcccccaaa would become a2blc5a3. If the "compressed" string would not become smaller than the original string, your method should return the original string. You can assume the string has only uppercase and lowercase letters (a - z).
- -Example 1:
- -- -Input: "aabcccccaaa" - -Output: "a2b1c5a3" - -- -
Example 2:
- -- -Input: "abbccd" - -Output: "abbccd" - -Explanation: - -The compressed string is "a1b2c2d1", which is longer than the original string. - -- -
Note:
- -- `0 <= S.length <= 50000` - -## Solutions - - - -### **Python3** - -```python -class Solution: - def compressString(self, S: str) -> str: - if len(S) < 2: - return S - p, q = 0, 1 - res = '' - while q < len(S): - if S[p] != S[q]: - res += (S[p] + str(q - p)) - p = q - q += 1 - res += (S[p] + str(q - p)) - return res if len(res) < len(S) else S -``` - -### **Java** - -```java -package src.main.java; -import java.util.*; - -public class Solution { - public String compressString(String S) { - if (S == null || S.length() < 2) { - return S; - } - char[] chars = S.toCharArray(); - int p = 0, q = 1, n = chars.length; - StringBuilder sb = new StringBuilder(); - while (q < n) { - if (chars[p] != chars[q]) { - sb.append(chars[p]).append(q - p); - p = q; - } - q += 1; - } - sb.append(chars[p]).append(q - p); - String res = sb.toString(); - return res.length() < n ? res : S; - } -} -``` - -### **...** - -``` - -``` - - diff --git a/leetcode/lcci/src.main/java/01.06.Compress String/Solution.py b/leetcode/lcci/src.main/java/01.06.Compress String/Solution.py deleted file mode 100644 index 5fbae1cd..00000000 --- a/leetcode/lcci/src.main/java/01.06.Compress String/Solution.py +++ /dev/null @@ -1,13 +0,0 @@ -class Solution: - def compressString(self, S: str) -> str: - if len(S) < 2: - return S - p, q = 0, 1 - res = '' - while q < len(S): - if S[p] != S[q]: - res += (S[p] + str(q - p)) - p = q - q += 1 - res += (S[p] + str(q - p)) - return res if len(res) < len(S) else S \ No newline at end of file diff --git a/leetcode/lcci/src.main/java/01.07.Rotate Matrix/README_EN.md b/leetcode/lcci/src.main/java/01.07.Rotate Matrix/README_EN.md deleted file mode 100644 index 3642d332..00000000 --- a/leetcode/lcci/src.main/java/01.07.Rotate Matrix/README_EN.md +++ /dev/null @@ -1,130 +0,0 @@ -# [01.07. Rotate Matrix](https://leetcode-cn.com/problems/rotate-matrix-lcci) - -[中文文档](/lcci/01.07.Rotate%20Matrix/README.md) - -## Description - -Given an image represented by an N x N matrix, where each pixel in the image is 4 bytes, write a method to rotate the image by 90 degrees. Can you do this in place?
- -- -
Example 1:
- -- -Given matrix = - -[ - - [1,2,3], - - [4,5,6], - - [7,8,9] - -], - - - -Rotate the matrix in place. It becomes: - -[ - - [7,4,1], - - [8,5,2], - - [9,6,3] - -] - -- -
Example 2:
- -- -Given matrix = - -[ - - [ 5, 1, 9,11], - - [ 2, 4, 8,10], - - [13, 3, 6, 7], - - [15,14,12,16] - -], - - - -Rotate the matrix in place. It becomes: - -[ - - [15,13, 2, 5], - - [14, 3, 4, 1], - - [12, 6, 8, 9], - - [16, 7,10,11] - -] - -- -## Solutions - - - -### **Python3** - -```python -class Solution: - def rotate(self, matrix: List[List[int]]) -> None: - """ - Do not return anything, modify matrix in-place instead. - """ - n = len(matrix) - for i in range(n // 2): - for j in range(i, n - 1 - i): - t = matrix[i][j] - matrix[i][j] = matrix[n - j - 1][i] - matrix[n - j - 1][i] = matrix[n - i - 1][n - j - 1] - matrix[n - i - 1][n - j - 1] = matrix[j][n - i - 1] - matrix[j][n - i - 1] = t - -``` - -### **Java** - -```java -package src.main.java; -import java.util.*; - -public class Solution { - public void rotate(int[][] matrix) { - int n = matrix.length; - for (int i = 0; i < n / 2; ++i) { - for (int j = i; j < n - 1 - i; ++j) { - int t = matrix[i][j]; - matrix[i][j] = matrix[n - j - 1][i]; - matrix[n - j - 1][i] = matrix[n - i - 1][n - j - 1]; - matrix[n - i - 1][n - j - 1] = matrix[j][n - i - 1]; - matrix[j][n - i - 1] = t; - } - } - } -} -``` - -### **...** - -``` - -``` - - diff --git a/leetcode/lcci/src.main/java/01.07.Rotate Matrix/Solution.py b/leetcode/lcci/src.main/java/01.07.Rotate Matrix/Solution.py deleted file mode 100644 index 950a8e3a..00000000 --- a/leetcode/lcci/src.main/java/01.07.Rotate Matrix/Solution.py +++ /dev/null @@ -1,13 +0,0 @@ -class Solution: - def rotate(self, matrix: List[List[int]]) -> None: - """ - Do not return anything, modify matrix in-place instead. - """ - n = len(matrix) - for i in range(n // 2): - for j in range(i, n - 1 - i): - t = matrix[i][j] - matrix[i][j] = matrix[n - j - 1][i] - matrix[n - j - 1][i] = matrix[n - i - 1][n - j - 1] - matrix[n - i - 1][n - j - 1] = matrix[j][n - i - 1] - matrix[j][n - i - 1] = t diff --git a/leetcode/lcci/src.main/java/01.08.Zero Matrix/README_EN.md b/leetcode/lcci/src.main/java/01.08.Zero Matrix/README_EN.md deleted file mode 100644 index cf931081..00000000 --- a/leetcode/lcci/src.main/java/01.08.Zero Matrix/README_EN.md +++ /dev/null @@ -1,144 +0,0 @@ -# [01.08. Zero Matrix](https://leetcode-cn.com/problems/zero-matrix-lcci) - -[中文文档](/lcci/01.08.Zero%20Matrix/README.md) - -## Description - -
Write an algorithm such that if an element in an MxN matrix is 0, its entire row and column are set to 0.
- -- -
Example 1:
- -- -Input: - -[ - - [1,1,1], - - [1,0,1], - - [1,1,1] - -] - -Output: - -[ - - [1,0,1], - - [0,0,0], - - [1,0,1] - -] - -- -
Example 2:
- -- -Input: - -[ - - [0,1,2,0], - - [3,4,5,2], - - [1,3,1,5] - -] - -Output: - -[ - - [0,0,0,0], - - [0,4,5,0], - - [0,3,1,0] - -] - -- -## Solutions - - - -### **Python3** - -```python -class Solution: - def setZeroes(self, matrix: List[List[int]]) -> None: - """ - Do not return anything, modify matrix in-place instead. - """ - rows, cols = len(matrix), len(matrix[0]) - zero_rows, zero_cols = set(), set() - for i in range(rows): - for j in range(cols): - if matrix[i][j] == 0: - zero_rows.add(i) - zero_cols.add(j) - - for i in zero_rows: - for j in range(cols): - matrix[i][j] = 0 - - for j in zero_cols: - for i in range(rows): - matrix[i][j] = 0 - - return matrix - -``` - -### **Java** - -```java -package src.main.java; -import java.util.*; - -public class Solution { - public void setZeroes(int[][] matrix) { - int rows = matrix.length, cols = matrix[0].length; - Set
Given two strings, s1
and s2
, write code to check if s2
is a rotation of s1
(e.g.,"waterbottle" is a rotation of"erbottlewat"). Can you use only one call to the method that checks if one word is a substring of another?
Example 1:
- -- -Input: s1 = "waterbottle", s2 = "erbottlewat" - -Output: True - -- -
Example 2:
- -- -Input: s1 = "aa", "aba" - -Output: False - -- -
- -
Note:
- -0 <= s1.length, s1.length <= 100000
Write code to remove duplicates from an unsorted linked list.
- -Example1:
- -- - Input: [1, 2, 3, 3, 2, 1] - - Output: [1, 2, 3] - -- -
Example2:
- -- - Input: [1, 1, 1, 1, 2] - - Output: [1, 2] - -- -
Note:
- -Follow Up:
- -How would you solve this problem if a temporary buffer is not allowed?
- -## Solutions - - - -### **Python3** - -```python -# Definition for singly-linked list. -# class ListNode: -# def __init__(self, x): -# self.val = x -# self.next = None - -class Solution: - def removeDuplicateNodes(self, head: ListNode) -> ListNode: - if head is None or head.next is None: - return head - cache = set() - cache.add(head.val) - cur, p = head, head.next - while p: - if p.val not in cache: - cur.next = p - cur = cur.next - cache.add(p.val) - p = p.next - cur.next = None - return head -``` - -### **Java** - -```java -/** - * Definition for singly-linked list. - * public class ListNode { - * int val; - * ListNode next; - * ListNode(int x) { val = x; } - * } - */ -package src.main.java; -import java.util.*; - -public class Solution { - public ListNode removeDuplicateNodes(ListNode head) { - if (head == null || head.next == null) { - return head; - } - SetImplement an algorithm to find the kth to last element of a singly linked list. Return the value of the element.
- -Note: This problem is slightly different from the original one in the book.
- -Example:
- -- -Input: 1->2->3->4->5 和 k = 2 - -Output: 4- -
Note:
- -k is always valid.
- -## Solutions - - - -### **Python3** - -```python -# Definition for singly-linked list. -# class ListNode: -# def __init__(self, x): -# self.val = x -# self.next = None - -class Solution: - def kthToLast(self, head: ListNode, k: int) -> int: - p = q = head - for _ in range(k): - q = q.next - while q: - p, q = p.next, q.next - return p.val -``` - -### **Java** - -```java -/** - * Definition for singly-linked list. - * public class ListNode { - * int val; - * ListNode next; - * ListNode(int x) { val = x; } - * } - */ -package src.main.java; -import java.util.*; - -public class Solution { - public int kthToLast(ListNode head, int k) { - ListNode p = head, q = head; - while (k-- > 0) { - q = q.next; - } - while (q != null) { - q = q.next; - p = p.next; - } - return p.val; - } -} -``` - -### **...** - -``` - -``` - - diff --git a/leetcode/lcci/src.main/java/02.02.Kth Node From End of List/Solution.py b/leetcode/lcci/src.main/java/02.02.Kth Node From End of List/Solution.py deleted file mode 100644 index 903ef471..00000000 --- a/leetcode/lcci/src.main/java/02.02.Kth Node From End of List/Solution.py +++ /dev/null @@ -1,14 +0,0 @@ -# Definition for singly-linked list. -# class ListNode: -# def __init__(self, x): -# self.val = x -# self.next = None - -class Solution: - def kthToLast(self, head: ListNode, k: int) -> int: - p = q = head - for _ in range(k): - q = q.next - while q: - p, q = p.next, q.next - return p.val \ No newline at end of file diff --git a/leetcode/lcci/src.main/java/02.03.Delete Middle Node/README_EN.md b/leetcode/lcci/src.main/java/02.03.Delete Middle Node/README_EN.md deleted file mode 100644 index 49fa8a7d..00000000 --- a/leetcode/lcci/src.main/java/02.03.Delete Middle Node/README_EN.md +++ /dev/null @@ -1,72 +0,0 @@ -# [02.03. Delete Middle Node](https://leetcode-cn.com/problems/delete-middle-node-lcci) - -[中文文档](/lcci/02.03.Delete%20Middle%20Node/README.md) - -## Description - -Implement an algorithm to delete a node in the middle (i.e., any node but the first and last node, not necessarily the exact middle) of a singly linked list, given only access to that node.
- -- -
Example:
- -- -Input: the node c from the linked list a->b->c->d->e->f - -Output: nothing is returned, but the new linked list looks like a->b->d->e->f - -- -## Solutions - - - -### **Python3** - -```python -# Definition for singly-linked list. -# class ListNode: -# def __init__(self, x): -# self.val = x -# self.next = None - -class Solution: - def deleteNode(self, node): - """ - :type node: ListNode - :rtype: void Do not return anything, modify node in-place instead. - """ - node.val = node.next.val - node.next = node.next.next -``` - -### **Java** - -```java -/** - * Definition for singly-linked list. - * public class ListNode { - * int val; - * ListNode next; - * ListNode(int x) { val = x; } - * } - */ -package src.main.java; -import java.util.*; - -public class Solution { - public void deleteNode(ListNode node) { - node.val = node.next.val; - node.next = node.next.next; - } -} -``` - -### **...** - -``` - -``` - - diff --git a/leetcode/lcci/src.main/java/02.03.Delete Middle Node/Solution.py b/leetcode/lcci/src.main/java/02.03.Delete Middle Node/Solution.py deleted file mode 100644 index 201e675b..00000000 --- a/leetcode/lcci/src.main/java/02.03.Delete Middle Node/Solution.py +++ /dev/null @@ -1,14 +0,0 @@ -# Definition for singly-linked list. -# class ListNode: -# def __init__(self, x): -# self.val = x -# self.next = None - -class Solution: - def deleteNode(self, node): - """ - :type node: ListNode - :rtype: void Do not return anything, modify node in-place instead. - """ - node.val = node.next.val - node.next = node.next.next \ No newline at end of file diff --git a/leetcode/lcci/src.main/java/02.04.Partition List/README_EN.md b/leetcode/lcci/src.main/java/02.04.Partition List/README_EN.md deleted file mode 100644 index 27183dd0..00000000 --- a/leetcode/lcci/src.main/java/02.04.Partition List/README_EN.md +++ /dev/null @@ -1,98 +0,0 @@ -# [02.04. Partition List](https://leetcode-cn.com/problems/partition-list-lcci) - -[中文文档](/lcci/02.04.Partition%20List/README.md) - -## Description - -
Write code to partition a linked list around a value x, such that all nodes less than x come before all nodes greater than or equal to x. If x is contained within the list, the values of x only need to be after the elements less than x (see below). The partition element x can appear anywhere in the "right partition"; it does not need to appear between the left and right partitions.
- -Example:
- -- -Input: head = 3->5->8->5->10->2->1, x = 5 - -Output: 3->1->2->10->5->5->8 - -- -## Solutions - - - -### **Python3** - -```python -# Definition for singly-linked list. -# class ListNode: -# def __init__(self, x): -# self.val = x -# self.next = None - -class Solution: - def partition(self, head: ListNode, x: int) -> ListNode: - if head is None or head.next is None: - return head - left, right = ListNode(-1), ListNode(-1) - p, q = left, right - while head: - t = head.next - head.next = None - if head.val < x: - p.next = head - p = p.next - else: - q.next = head - q = q.next - head = t - p.next = right.next - return left.next -``` - -### **Java** - -```java -/** - * Definition for singly-linked list. - * public class ListNode { - * int val; - * ListNode next; - * ListNode(int x) { val = x; } - * } - */ -package src.main.java; -import java.util.*; - -public class Solution { - public ListNode partition(ListNode head, int x) { - if (head == null || head.next == null) { - return head; - } - ListNode left = new ListNode(-1); - ListNode right = new ListNode(-1); - ListNode p = left, q = right; - while (head != null) { - ListNode t = head.next; - head.next = null; - if (head.val < x) { - p.next = head; - p = p.next; - } else { - q.next = head; - q = q.next; - } - head = t; - } - p.next = right.next; - return left.next; - } -} -``` - -### **...** - -``` - -``` - - diff --git a/leetcode/lcci/src.main/java/02.04.Partition List/Solution.py b/leetcode/lcci/src.main/java/02.04.Partition List/Solution.py deleted file mode 100644 index 3d941f03..00000000 --- a/leetcode/lcci/src.main/java/02.04.Partition List/Solution.py +++ /dev/null @@ -1,25 +0,0 @@ -# Definition for singly-linked list. -# class ListNode: -# def __init__(self, x): -# self.val = x -# self.next = None - - -class Solution: - def partition(self, head: ListNode, x: int) -> ListNode: - if head is None or head.next is None: - return head - left, right = ListNode(-1), ListNode(-1) - p, q = left, right - while head: - t = head.next - head.next = None - if head.val < x: - p.next = head - p = p.next - else: - q.next = head - q = q.next - head = t - p.next = right.next - return left.next diff --git a/leetcode/lcci/src.main/java/02.05.Sum Lists/README_EN.md b/leetcode/lcci/src.main/java/02.05.Sum Lists/README_EN.md deleted file mode 100644 index af5d3a83..00000000 --- a/leetcode/lcci/src.main/java/02.05.Sum Lists/README_EN.md +++ /dev/null @@ -1,102 +0,0 @@ -# [02.05. Sum Lists](https://leetcode-cn.com/problems/sum-lists-lcci) - -[中文文档](/lcci/02.05.Sum%20Lists/README.md) - -## Description - -
You have two numbers represented by a linked list, where each node contains a single digit. The digits are stored in reverse order, such that the 1's digit is at the head of the list. Write a function that adds the two numbers and returns the sum as a linked list.
- -- -
Example:
- -- -Input: (7 -> 1 -> 6) + (5 -> 9 -> 2). That is, 617 + 295. - -Output: 2 -> 1 -> 9. That is, 912. - -- -
Follow Up: Suppose the digits are stored in forward order. Repeat the above problem.
- -Example:
- -- -Input: (6 -> 1 -> 7) + (2 -> 9 -> 5). That is, 617 + 295. - -Output: 9 -> 1 -> 2. That is, 912. - -- -## Solutions - - - -### **Python3** - -```python -# Definition for singly-linked list. -# class ListNode: -# def __init__(self, x): -# self.val = x -# self.next = None - -class Solution: - def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: - p = ListNode(-1) - carry, t = 0, p - while l1 or l2: - s = (0 if l1 is None else l1.val) + (0 if l2 is None else l2.val) + carry - carry = 1 if s > 9 else 0 - t.next = ListNode(s % 10) - t = t.next - l1 = l1.next if l1 else l1 - l2 = l2.next if l2 else l2 - t.next = None if carry == 0 else ListNode(carry) - return p.next - - -``` - -### **Java** - -```java -/** - * Definition for singly-linked list. - * public class ListNode { - * int val; - * ListNode next; - * ListNode(int x) { val = x; } - * } - */ -package src.main.java; -import java.util.*; - -public class Solution { - public ListNode addTwoNumbers(ListNode l1, ListNode l2) { - ListNode p = new ListNode(-1); - int carry = 0; - ListNode t = p; - while (l1 != null || l2 != null) { - int s = (l1 == null ? 0 : l1.val) + (l2 == null ? 0 : l2.val) + carry; - t.next = new ListNode(s % 10); - carry = s > 9 ? 1 : 0; - t = t.next; - l1 = l1 == null ? l1 : l1.next; - l2 = l2 == null ? l2 : l2.next; - } - t.next = carry == 0 ? null : new ListNode(carry); - return p.next; - } -} -``` - -### **...** - -``` - -``` - - diff --git a/leetcode/lcci/src.main/java/02.05.Sum Lists/Solution.py b/leetcode/lcci/src.main/java/02.05.Sum Lists/Solution.py deleted file mode 100644 index 8165bb4c..00000000 --- a/leetcode/lcci/src.main/java/02.05.Sum Lists/Solution.py +++ /dev/null @@ -1,21 +0,0 @@ -# Definition for singly-linked list. -# class ListNode: -# def __init__(self, x): -# self.val = x -# self.next = None - - -class Solution: - def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: - p = ListNode(-1) - carry, t = 0, p - while l1 or l2: - s = (0 if l1 is None else l1.val) + \ - (0 if l2 is None else l2.val) + carry - carry = 1 if s > 9 else 0 - t.next = ListNode(s % 10) - t = t.next - l1 = l1.next if l1 else l1 - l2 = l2.next if l2 else l2 - t.next = None if carry == 0 else ListNode(carry) - return p.next diff --git a/leetcode/lcci/src.main/java/02.06.Palindrome Linked List/README_EN.md b/leetcode/lcci/src.main/java/02.06.Palindrome Linked List/README_EN.md deleted file mode 100644 index 04f6540e..00000000 --- a/leetcode/lcci/src.main/java/02.06.Palindrome Linked List/README_EN.md +++ /dev/null @@ -1,120 +0,0 @@ -# [02.06. Palindrome Linked List](https://leetcode-cn.com/problems/palindrome-linked-list-lcci) - -[中文文档](/lcci/02.06.Palindrome%20Linked%20List/README.md) - -## Description - -
Implement a function to check if a linked list is a palindrome.
- -- -
Example 1:
- -- -Input: 1->2 - -Output: false - -- -
Example 2:
- -- -Input: 1->2->2->1 - -Output: true - -- -
- -
Follow up:
-
-Could you do it in O(n) time and O(1) space?
Given a circular linked list, implement an algorithm that returns the node at the beginning of the loop.
- -Circular linked list: A (corrupt) linked list in which a node's next pointer points to an earlier node, so as to make a loop in the linked list.
- -Example 1:
- -- -Input: head = [3,2,0,-4], pos = 1 - -Output: tail connects to node index 1- -
Example 2:
- -- -Input: head = [1,2], pos = 0 - -Output: tail connects to node index 0- -
Example 3:
- -- -Input: head = [1], pos = -1 - -Output: no cycle- -
Follow Up:
-
-Can you solve it without using additional space?
Describe how you could use a single array to implement three stacks.
- -Yout should implement push(stackNum, value)
、pop(stackNum)
、isEmpty(stackNum)
、peek(stackNum)
methods. stackNum
is the index of the stack. value
is the value that pushed to the stack.
The constructor requires a stackSize
parameter, which represents the size of each stack.
Example1:
- -- - Input: - -["TripleInOne", "push", "push", "pop", "pop", "pop", "isEmpty"] - -[[1], [0, 1], [0, 2], [0], [0], [0], [0]] - - Output: - -[null, null, null, 1, -1, -1, true] - -Explanation: When the stack is empty, `pop, peek` return -1. When the stack is full, `push` does nothing. - -- -
Example2:
- -- - Input: - -["TripleInOne", "push", "push", "push", "pop", "pop", "pop", "peek"] - -[[2], [0, 1], [0, 2], [0, 3], [0], [0], [0], [0]] - - Output: - -[null, null, null, null, 2, 1, -1, -1] - -- -## Solutions - - - -### **Python3** - -```python -class TripleInOne: - - def __init__(self, stackSize: int): - self._capacity = stackSize - self._s = [[], [], []] - - def push(self, stackNum: int, value: int) -> None: - if len(self._s[stackNum]) < self._capacity: - self._s[stackNum].append(value) - - def pop(self, stackNum: int) -> int: - return -1 if self.isEmpty(stackNum) else self._s[stackNum].pop() - - def peek(self, stackNum: int) -> int: - return -1 if self.isEmpty(stackNum) else self._s[stackNum][-1] - - def isEmpty(self, stackNum: int) -> bool: - return len(self._s[stackNum]) == 0 - - -# Your TripleInOne object will be instantiated and called as such: -# obj = TripleInOne(stackSize) -# obj.push(stackNum,value) -# param_2 = obj.pop(stackNum) -# param_3 = obj.peek(stackNum) -# param_4 = obj.isEmpty(stackNum) -``` - -### **Java** - -```java -class TripleInOne { - private int[] s; - private int capacity; - - public TripleInOne(int stackSize) { - s = new int[stackSize * 3 + 3]; - capacity = stackSize; - } - - public void push(int stackNum, int value) { - if (s[stackNum + 3 * capacity] < capacity) { - s[s[stackNum + 3 * capacity] * 3 + stackNum] = value; - ++s[stackNum + 3 * capacity]; - } - } - - public int pop(int stackNum) { - if (isEmpty(stackNum)) { - return -1; - } - --s[stackNum + 3 * capacity]; - return s[s[stackNum + 3 * capacity] * 3 + stackNum]; - } - - public int peek(int stackNum) { - return isEmpty(stackNum) ? -1 : s[(s[stackNum + 3 * capacity] - 1) * 3 + stackNum]; - } - - public boolean isEmpty(int stackNum) { - return s[stackNum + 3 * capacity] == 0; - } -} - -/** - * Your TripleInOne object will be instantiated and called as such: - * TripleInOne obj = new TripleInOne(stackSize); - * obj.push(stackNum,value); - * int param_2 = obj.pop(stackNum); - * int param_3 = obj.peek(stackNum); - * boolean param_4 = obj.isEmpty(stackNum); - */ -``` - -### **...** - -``` - -``` - - diff --git a/leetcode/lcci/src.main/java/03.01.Three in One/Solution.py b/leetcode/lcci/src.main/java/03.01.Three in One/Solution.py deleted file mode 100644 index c84c645a..00000000 --- a/leetcode/lcci/src.main/java/03.01.Three in One/Solution.py +++ /dev/null @@ -1,26 +0,0 @@ -class TripleInOne: - - def __init__(self, stackSize: int): - self._capacity = stackSize - self._s = [[], [], []] - - def push(self, stackNum: int, value: int) -> None: - if len(self._s[stackNum]) < self._capacity: - self._s[stackNum].append(value) - - def pop(self, stackNum: int) -> int: - return -1 if self.isEmpty(stackNum) else self._s[stackNum].pop() - - def peek(self, stackNum: int) -> int: - return -1 if self.isEmpty(stackNum) else self._s[stackNum][-1] - - def isEmpty(self, stackNum: int) -> bool: - return len(self._s[stackNum]) == 0 - - -# Your TripleInOne object will be instantiated and called as such: -# obj = TripleInOne(stackSize) -# obj.push(stackNum,value) -# param_2 = obj.pop(stackNum) -# param_3 = obj.peek(stackNum) -# param_4 = obj.isEmpty(stackNum) diff --git a/leetcode/lcci/src.main/java/03.02.Min Stack/README_EN.md b/leetcode/lcci/src.main/java/03.02.Min Stack/README_EN.md deleted file mode 100644 index 57fb34d7..00000000 --- a/leetcode/lcci/src.main/java/03.02.Min Stack/README_EN.md +++ /dev/null @@ -1,117 +0,0 @@ -# [03.02. Min Stack](https://leetcode-cn.com/problems/min-stack-lcci) - -[中文文档](/lcci/03.02.Min%20Stack/README.md) - -## Description - -
How would you design a stack which, in addition to push and pop, has a function min which returns the minimum element? Push, pop and min should all operate in 0(1) time.
- -Example:
- -- -MinStack minStack = new MinStack(); - -minStack.push(-2); - -minStack.push(0); - -minStack.push(-3); - -minStack.getMin(); --> return -3. - -minStack.pop(); - -minStack.top(); --> return 0. - -minStack.getMin(); --> return -2.- -## Solutions - - - -### **Python3** - -```python -class MinStack: - - def __init__(self): - """ - initialize your data structure here. - """ - self._s1 = [] - self._s2 = [] - - - def push(self, x: int) -> None: - self._s1.append(x) - self._s2.append(x if len(self._s2) == 0 or self._s2[-1] >= x else self._s2[-1]) - - def pop(self) -> None: - self._s1.pop() - self._s2.pop() - - def top(self) -> int: - return self._s1[-1] - - def getMin(self) -> int: - return self._s2[-1] - - -# Your MinStack object will be instantiated and called as such: -# obj = MinStack() -# obj.push(x) -# obj.pop() -# param_3 = obj.top() -# param_4 = obj.getMin() -``` - -### **Java** - -```java -class MinStack { - private Stack
Implement a MyQueue class which implements a queue using two stacks.
- - - -Example:
- -- -MyQueue queue = new MyQueue(); - - - -queue.push(1); - -queue.push(2); - -queue.peek(); // return 1 - -queue.pop(); // return 1 - -queue.empty(); // return false- -
- -
Notes:
- -push to top
, peek/pop from top
, size
, and is empty
operations are valid.- -## Solutions - - - -### **Python3** - -```python -class MyQueue: - - def __init__(self): - """ - Initialize your data structure here. - """ - self._s1, self._s2 = [], [] - - - def push(self, x: int) -> None: - """ - Push element x to the back of queue. - """ - self._s1.append(x) - - - def pop(self) -> int: - """ - Removes the element from in front of queue and returns that element. - """ - if len(self._s2) == 0: - while self._s1: - self._s2.append(self._s1.pop()) - return self._s2.pop() - - - def peek(self) -> int: - """ - Get the front element. - """ - if len(self._s2) == 0: - while self._s1: - self._s2.append(self._s1.pop()) - return self._s2[-1] - - - def empty(self) -> bool: - """ - Returns whether the queue is empty. - """ - return len(self._s1) + len(self._s2) == 0 - - - -# Your MyQueue object will be instantiated and called as such: -# obj = MyQueue() -# obj.push(x) -# param_2 = obj.pop() -# param_3 = obj.peek() -# param_4 = obj.empty() -``` - -### **Java** - -```java -class MyQueue { - private Stack
Write a program to sort a stack such that the smallest items are on the top. You can use an additional temporary stack, but you may not copy the elements into any other data structure (such as an array). The stack supports the following operations: push
, pop
, peek
, and isEmpty
. When the stack is empty, peek
should return -1.
Example1:
- -- - Input: - -["SortedStack", "push", "push", "peek", "pop", "peek"] - -[[], [1], [2], [], [], []] - - Output: - -[null,null,null,1,null,2] - -- -
Example2:
- -- - Input: - -["SortedStack", "pop", "pop", "push", "pop", "isEmpty"] - -[[], [], [], [1], [], []] - - Output: - -[null,null,null,null,null,true] - -- -
Note:
- -An animal shelter, which holds only dogs and cats, operates on a strictly"first in, first out" basis. People must adopt either the"oldest" (based on arrival time) of all animals at the shelter, or they can select whether they would prefer a dog or a cat (and will receive the oldest animal of that type). They cannot select which specific animal they would like. Create the data structures to maintain this system and implement operations such as enqueue
, dequeueAny
, dequeueDog
, and dequeueCat
. You may use the built-in Linked list data structure.
enqueue
method has a animal
parameter, animal[0]
represents the number of the animal, animal[1]
represents the type of the animal, 0 for cat and 1 for dog.
dequeue*
method returns [animal number, animal type]
, if there's no animal that can be adopted, return [-1, -1]
.
Example1:
- -- - Input: - -["AnimalShelf", "enqueue", "enqueue", "dequeueCat", "dequeueDog", "dequeueAny"] - -[[], [[0, 0]], [[1, 0]], [], [], []] - - Output: - -[null,null,null,[0,0],[-1,-1],[1,0]] - -- -
Example2:
- -- - Input: - -["AnimalShelf", "enqueue", "enqueue", "enqueue", "dequeueDog", "dequeueCat", "dequeueAny"] - -[[], [[0, 0]], [[1, 0]], [[2, 1]], [], [], []] - - Output: - -[null,null,null,null,[2,1],[0,0],[1,0]] - -- -
Note:
- -Implement a function to check if a binary tree is balanced. For the purposes of this question, a balanced tree is defined to be a tree such that the heights of the two subtrees of any node never differ by more than one.
- -
-
-Example 1:
- -Given tree [3,9,20,null,null,15,7] - - 3 - - / \ - - 9 20 - - / \ - - 15 7 - -return true.- -
Example 2:
- -- -Given [1,2,2,3,3,null,null,4,4] - - 1 - - / \ - - 2 2 - - / \ - - 3 3 - - / \ - -4 4 - -return false.- -
- -## Solutions - - - -### **Python3** - -```python -# Definition for a binary tree node. -# class TreeNode: -# def __init__(self, x): -# self.val = x -# self.left = None -# self.right = None - -class Solution: - def isBalanced(self, root: TreeNode) -> bool: - if not root: - return True - l, r = self._height(root.left), self._height(root.right) - return abs(l - r) < 2 and self.isBalanced(root.left) and self.isBalanced(root.right) - - def _height(self, node): - if not node: - return 0 - return 1 + max(self._height(node.left), self._height(node.right)) -``` - -### **Java** - -```java -/** - * Definition for a binary tree node. - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode(int x) { val = x; } - * } - */ -package src.main.java; -import java.util.*; - -public class Solution { - public boolean isBalanced(TreeNode root) { - if (root == null) { - return true; - } - int l = height(root.left), r = height(root.right); - return Math.abs(l - r) < 2 && isBalanced(root.left) && isBalanced(root.right); - } - - private int height(TreeNode node) { - if (node == null) { - return 0; - } - return 1 + Math.max(height(node.left), height(node.right)); - } -} -``` - -### **...** - -``` - -``` - - diff --git a/leetcode/lcci/src.main/java/04.04.Check Balance/Solution.py b/leetcode/lcci/src.main/java/04.04.Check Balance/Solution.py deleted file mode 100644 index df117271..00000000 --- a/leetcode/lcci/src.main/java/04.04.Check Balance/Solution.py +++ /dev/null @@ -1,19 +0,0 @@ -# Definition for a binary tree node. -# class TreeNode: -# def __init__(self, x): -# self.val = x -# self.left = None -# self.right = None - - -class Solution: - def isBalanced(self, root: TreeNode) -> bool: - if not root: - return True - l, r = self._height(root.left), self._height(root.right) - return abs(l - r) < 2 and self.isBalanced(root.left) and self.isBalanced(root.right) - - def _height(self, node): - if not node: - return 0 - return 1 + max(self._height(node.left), self._height(node.right)) diff --git a/leetcode/lcci/src.main/java/04.05.Legal Binary Search Tree/README_EN.md b/leetcode/lcci/src.main/java/04.05.Legal Binary Search Tree/README_EN.md deleted file mode 100644 index 6f49ba8f..00000000 --- a/leetcode/lcci/src.main/java/04.05.Legal Binary Search Tree/README_EN.md +++ /dev/null @@ -1,124 +0,0 @@ -# [04.05. Legal Binary Search Tree](https://leetcode-cn.com/problems/legal-binary-search-tree-lcci) - -[中文文档](/lcci/04.05.Legal%20Binary%20Search%20Tree/README.md) - -## Description - -
Implement a function to check if a binary tree is a binary search tree.
- -Example 1:
- -- -Input: - - 2 - - / \ - - 1 3 - -Output: true - -- -
Example 2:
- -- -Input: - - 5 - - / \ - - 1 4 - - / \ - - 3 6 - -Output: false - -Explanation: Input: [5,1,4,null,null,3,6]. - - the value of root node is 5, but its right child has value 4.- -## Solutions - - - -### **Python3** - -```python -# Definition for a binary tree node. -# class TreeNode: -# def __init__(self, x): -# self.val = x -# self.left = None -# self.right = None - -class Solution: - res, t = True, None - def isValidBST(self, root: TreeNode) -> bool: - self.isValid(root) - return self.res - - def isValid(self, root): - if not root: - return - self.isValid(root.left) - if self.t is None or self.t < root.val: - self.t = root.val - else: - self.res = False - return - self.isValid(root.right) -``` - -### **Java** - -```java -/** - * Definition for a binary tree node. - * public class TreeNode { - * int val; - * TreeNode left; - * TreeNode right; - * TreeNode(int x) { val = x; } - * } - */ -package src.main.java; -import java.util.*; - -public class Solution { - private boolean res = true; - private Integer t = null; - public boolean isValidBST(TreeNode root) { - isValid(root); - return res; - } - - private void isValid(TreeNode root) { - if (root == null) { - return; - } - isValid(root.left); - if (t == null || t < root.val) { - t = root.val; - } else { - res = false; - return; - } - isValid(root.right); - } -} -``` - -### **...** - -``` - -``` - - diff --git a/leetcode/lcci/src.main/java/04.05.Legal Binary Search Tree/Solution.py b/leetcode/lcci/src.main/java/04.05.Legal Binary Search Tree/Solution.py deleted file mode 100644 index e9b4aaf5..00000000 --- a/leetcode/lcci/src.main/java/04.05.Legal Binary Search Tree/Solution.py +++ /dev/null @@ -1,23 +0,0 @@ -# Definition for a binary tree node. -# class TreeNode: -# def __init__(self, x): -# self.val = x -# self.left = None -# self.right = None - -class Solution: - res, t = True, None - def isValidBST(self, root: TreeNode) -> bool: - self.isValid(root) - return self.res - - def isValid(self, root): - if not root: - return - self.isValid(root.left) - if self.t is None or self.t < root.val: - self.t = root.val - else: - self.res = False - return - self.isValid(root.right) \ No newline at end of file diff --git a/leetcode/lcci/src.main/java/04.08.First Common Ancestor/README_EN.md b/leetcode/lcci/src.main/java/04.08.First Common Ancestor/README_EN.md deleted file mode 100644 index f595518c..00000000 --- a/leetcode/lcci/src.main/java/04.08.First Common Ancestor/README_EN.md +++ /dev/null @@ -1,112 +0,0 @@ -# [04.08. First Common Ancestor](https://leetcode-cn.com/problems/first-common-ancestor-lcci) - -[中文文档](/lcci/04.08.First%20Common%20Ancestor/README.md) - -## Description - -
Design an algorithm and write code to find the first common ancestor of two nodes in a binary tree. Avoid storing additional nodes in a data structure. NOTE: This is not necessarily a binary search tree.
- -For example, Given the following tree: root = [3,5,1,6,2,0,8,null,null,7,4]
- -- - 3 - - / \ - - 5 1 - - / \ / \ - -6 2 0 8 - - / \ - - 7 4 - -- -
Example 1:
- -- -Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1 - -Input: 3 - -Explanation: The first common ancestor of node 5 and node 1 is node 3.- -
Example 2:
- -- -Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4 - -Output: 5 - -Explanation: The first common ancestor of node 5 and node 4 is node 5.- -
Notes:
- -T1 and T2 are two very large binary trees, with T1 much bigger than T2. Create an algorithm to determine if T2 is a subtree of T1.
- -A tree T2 is a subtree of T1 if there exists a node n in T1 such that the subtree of n is identical to T2. That is, if you cut off the tree at node n, the two trees would be identical.
- -Example1:
- -- - Input: t1 = [1, 2, 3], t2 = [2] - - Output: true - -- -
Example2:
- -- - Input: t1 = [1, null, 2, 4], t2 = [3, 2] - - Output: false - -- -
Note:
- -You are given a binary tree in which each node contains an integer value (which might be positive or negative). Design an algorithm to count the number of paths that sum to a given value. The path does not need to start or end at the root or a leaf, but it must go downwards (traveling only from parent nodes to child nodes).
- -Example:
-
-Given the following tree and sum = 22,
- - 5 - - / \ - - 4 8 - - / / \ - - 11 13 4 - - / \ / \ - - 7 2 5 1 - -- -
Output:
- -- -3 - -Explanation: Paths that have sum 22 are: [5,4,11,2], [5,8,4,5], [4,11,7]- -
Note:
- -node number <= 10000
You are given two 32-bit numbers, N and M, and two bit positions, i and j. Write a method to insert M into N such that M starts at bit j and ends at bit i. You can assume that the bits j through i have enough space to fit all of M. That is, if M = 10011, you can assume that there are at least 5 bits between j and i. You would not, for example, have j = 3 and i = 2, because M could not fully fit between bit 3 and bit 2.
- -Example1:
- -- - Input: N = 10000000000, M = 10011, i = 2, j = 6 - - Output: N = 10001001100 - -- -
Example2:
- -- - Input: N = 0, M = 11111, i = 0, j = 4 - - Output: N = 11111 - -- -## Solutions - - - -### **Python3** - -```python - -``` - -### **Java** - -```java -package src.main.java; -import java.util.*; - -public class Solution { - public int insertBits(int N, int M, int i, int j) { - for (int k = i; k <= j; k++) { - N &= ~(1 << k); - } - return N ^ (M << i); - } -} -``` - -### **...** - -``` - -``` - - diff --git a/leetcode/lcci/src.main/java/05.06.Convert Integer/README_EN.md b/leetcode/lcci/src.main/java/05.06.Convert Integer/README_EN.md deleted file mode 100644 index 35ec9562..00000000 --- a/leetcode/lcci/src.main/java/05.06.Convert Integer/README_EN.md +++ /dev/null @@ -1,64 +0,0 @@ -# [05.06. Convert Integer](https://leetcode-cn.com/problems/convert-integer-lcci) - -[中文文档](/lcci/05.06.Convert%20Integer/README.md) - -## Description - -
Write a function to determine the number of bits you would need to flip to convert integer A to integer B.
- -Example1:
- -- - Input: A = 29 (0b11101), B = 15 (0b01111) - - Output: 2 - -- -
Example2:
- -- - Input: A = 1,B = 2 - - Output: 2 - -- -
Note:
- --2147483648 <= A, B <= 2147483647
Write a program to swap odd and even bits in an integer with as few instructions as possible (e.g., bit 0 and bit 1 are swapped, bit 2 and bit 3 are swapped, and so on).
- -Example1:
- -- - Input: num = 2(0b10) - - Output 1 (0b01) - -- -
Example2:
- -- - Input: num = 3 - - Output: 3 - -- -
Note:
- -0 <= num <=
2^30 - 1A child is running up a staircase with n steps and can hop either 1 step, 2 steps, or 3 steps at a time. Implement a method to count how many possible ways the child can run up the stairs. The result may be large, so return it modulo 1000000007.
- -Example1:
- -- - Input: n = 3 - - Output: 4 - -- -
Example2:
- -- - Input: n = 5 - - Output: 13 - -- -
Note:
- -1. `1 <= n <= 1000000` - -## Solutions - - - -### **Python3** - -```python -class Solution: - def waysToStep(self, n: int) -> int: - if n < 3: - return n - a, b, c = 1, 2, 4 - for _ in range(4, n + 1): - a, b, c = b, c, (a + b + c) % 1000000007 - return c -``` - -### **Java** - -```java -package src.main.java; -import java.util.*; - -public class Solution { - public int waysToStep(int n) { - if (n < 3) { - return n; - } - int a = 1, b = 2, c = 4; - for (int i = 4; i <= n; ++i) { - int t = a; - a = b; - b = c; - c = ((a + b) % 1000000007 + t) % 1000000007; - } - return c; - } -} -``` - -### **C++** - -```cpp -package src.main.java; -import java.util.*; - -public class Solution { -public: - int waysToStep(int n) { - if (n < 3) { - return n; - } - int a = 1, b = 2, c = 4, i = 4; - while (i++ <= n) { - int t = ((a + b) % 1000000007 + c) % 1000000007; - a = b; - b = c; - c = t; - } - return c; - } -}; -``` - - diff --git a/leetcode/lcci/src.main/java/08.01.Three Steps Problem/Solution.c b/leetcode/lcci/src.main/java/08.01.Three Steps Problem/Solution.c deleted file mode 100644 index f0d26e0e..00000000 --- a/leetcode/lcci/src.main/java/08.01.Three Steps Problem/Solution.c +++ /dev/null @@ -1,16 +0,0 @@ -int waysToStep(int n) -{ - if (n < 3) - { - return n; - } - int a = 1, b = 2, c = 4, i = 4; - while (i++ <= n) - { - int t = ((a + b) % 1000000007 + c) % 1000000007; - a = b; - b = c; - c = t; - } - return c; -} \ No newline at end of file diff --git a/leetcode/lcci/src.main/java/08.01.Three Steps Problem/Solution.cpp b/leetcode/lcci/src.main/java/08.01.Three Steps Problem/Solution.cpp deleted file mode 100644 index c06624ce..00000000 --- a/leetcode/lcci/src.main/java/08.01.Three Steps Problem/Solution.cpp +++ /dev/null @@ -1,19 +0,0 @@ -package src.main.java; -import java.util.*; - -public class Solution { -public: - int waysToStep(int n) { - if (n < 3) { - return n; - } - int a = 1, b = 2, c = 4, i = 4; - while (i++ <= n) { - int t = ((a + b) % 1000000007 + c) % 1000000007; - a = b; - b = c; - c = t; - } - return c; - } -}; \ No newline at end of file diff --git a/leetcode/lcci/src.main/java/08.01.Three Steps Problem/Solution.py b/leetcode/lcci/src.main/java/08.01.Three Steps Problem/Solution.py deleted file mode 100644 index ec377133..00000000 --- a/leetcode/lcci/src.main/java/08.01.Three Steps Problem/Solution.py +++ /dev/null @@ -1,8 +0,0 @@ -class Solution: - def waysToStep(self, n: int) -> int: - if n < 3: - return n - a, b, c = 1, 2, 4 - for _ in range(4, n + 1): - a, b, c = b, c, (a + b + c) % 1000000007 - return c \ No newline at end of file diff --git a/leetcode/lcci/src.main/java/08.09.Bracket/README_EN.md b/leetcode/lcci/src.main/java/08.09.Bracket/README_EN.md deleted file mode 100644 index 7f59a047..00000000 --- a/leetcode/lcci/src.main/java/08.09.Bracket/README_EN.md +++ /dev/null @@ -1,94 +0,0 @@ -# [08.09. Bracket](https://leetcode-cn.com/problems/bracket-lcci) - -[中文文档](/lcci/08.09.Bracket/README.md) - -## Description - -Implement an algorithm to print all valid (e.g., properly opened and closed) combinations of n pairs of parentheses.
- -Note: The result set should not contain duplicated subsets.
- -For example, given n = 3, the result should be:
- -- -[ - - "((()))", - - "(()())", - - "(())()", - - "()(())", - - "()()()" - -] - -- -## Solutions - - - -### **Python3** - -```python -class Solution: - def generateParenthesis(self, n: int) -> List[str]: - res = [] - def generate(state, left, right): - if left > right: - return - if right == 0: - res.append(state) - return - if left > 0: - generate(state + '(', left - 1, right) - if right > 0: - generate(state + ')', left, right - 1) - generate('', n, n) - return res -``` - -### **Java** - -```java -package src.main.java; -import java.util.*; - -public class Solution { - List
Implement the "paint fill" function that one might see on many image editing programs. That is, given a screen (represented by a two-dimensional array of colors), a point, and a new color, fill in the surrounding area until the color changes from the original color.
- -Example1:
- -- -Input: - -image = [[1,1,1],[1,1,0],[1,0,1]] - -sr = 1, sc = 1, newColor = 2 - -Output: [[2,2,2],[2,2,0],[2,0,1]] - -Explanation: - -From the center of the image (with position (sr, sc) = (1, 1)), all pixels connected - -by a path of the same color as the starting pixel are colored with the new color. - -Note the bottom corner is not colored 2, because it is not 4-directionally connected - -to the starting pixel.- -
Note:
- -image
and image[0]
will be in the range [1, 50]
.0 <= sr < image.length
and 0 <= sc < image[0].length
.image[i][j]
and newColor
will be an integer in [0, 65535]
.Given an M x N matrix in which each row and each column is sorted in ascending order, write a method to find an element.
- -Example:
- -Given matrix:
- -- -[ - - [1, 4, 7, 11, 15], - - [2, 5, 8, 12, 19], - - [3, 6, 9, 16, 22], - - [10, 13, 14, 17, 24], - - [18, 21, 23, 26, 30] - -] - -- -
Given target = 5, return true.
Given target = 20, return false.
Write a function to swap a number in place (that is, without temporary vari ables).
- -Example:
- -- -Input: numbers = [1,2] - -Output: [2,1] - -- -
Note:
- -numbers.length == 2
Given two arrays of integers, compute the pair of values (one value in each array) with the smallest (non-negative) difference. Return the difference.
- -Example:
- -- -Input: {1, 3, 15, 11, 2}, {23, 127, 235, 19, 8} - -Output: 3, the pair (11, 8) - -- -
Note:
- -1 <= a.length, b.length <= 100000
-2147483648 <= a[i], b[i] <= 2147483647
Given a list of people with their birth and death years, implement a method to compute the year with the most number of people alive. You may assume that all people were born between 1900 and 2000 (inclusive). If a person was alive during any portion of that year, they should be included in that year's count. For example, Person (birth= 1908, death= 1909) is included in the counts for both 1908 and 1909.
- -If there are more than one years that have the most number of people alive, return the smallest one.
- -Example:
- -- -Input: - -birth = {1900, 1901, 1950} - -death = {1948, 1951, 2000} - -Output: 1901 - -- -
Note:
- -0 < birth.length == death.length <= 10000
birth[i] <= death[i]
You are building a diving board by placing a bunch of planks of wood end-to-end. There are two types of planks, one of length shorter
and one of length longer
. You must use exactly K
planks of wood. Write a method to generate all possible lengths for the diving board.
return all lengths in non-decreasing order.
- -Example:
- -- -Input: - -shorter = 1 - -longer = 2 - -k = 3 - -Output: {3,4,5,6} - -- -
Note:
- -Given two arrays of integers, find a pair of values (one value from each array) that you can swap to give the two arrays the same sum.
- -Return an array, where the first element is the element in the first array that will be swapped, and the second element is another one in the second array. If there are more than one answers, return any one of them. If there is no answer, return an empty array.
- -Example:
- -- -Input: array1 = [4, 1, 2, 1, 1, 2], array2 = [3, 6, 3, 3] - -Output: [1, 3] - -- -
Example:
- -
-
-Input: array1 = [1, 2, 3], array2 = [4, 5, 6]
-
-Output: []
-
-Note:
- -1 <= array1.length, array2.length <= 100000
Write a function that adds two numbers. You should not use + or any arithmetic operators.
- -Example:
- -- -Input: a = 1, b = 1 - -Output: 2- -
- -
Note:
- -a
and b
may be 0 or negative.An array contains all the integers from 0 to n, except for one number which is missing. Write code to find the missing integer. Can you do it in O(n) time?
- -Note: This problem is slightly different from the original one the book.
- -Example 1:
- -- -Input: [3,0,1] - -Output: 2- -
- -
Example 2:
- -- -Input: [9,6,4,2,3,5,7,0,1] - -Output: 8 - -- -## Solutions - - - -### **Python3** - -```python -class Solution: - def missingNumber(self, nums: List[int]) -> int: - res = 0 - for i, num in enumerate(nums): - res ^= i - res ^= num - res ^= len(nums) - return res -``` - -### **Java** - -```java -package src.main.java; -import java.util.*; - -public class Solution { - public int missingNumber(int[] nums) { - int res = 0, n = nums.length; - for (int i = 0; i < n; ++i) { - res ^= i; - res ^= nums[i]; - } - res ^= n; - return res; - } -} -``` - -### **...** - -``` - -``` - - diff --git a/leetcode/lcci/src.main/java/17.04.Missing Number/Solution.py b/leetcode/lcci/src.main/java/17.04.Missing Number/Solution.py deleted file mode 100644 index 8de166bf..00000000 --- a/leetcode/lcci/src.main/java/17.04.Missing Number/Solution.py +++ /dev/null @@ -1,8 +0,0 @@ -class Solution: - def missingNumber(self, nums: List[int]) -> int: - res = 0 - for i, num in enumerate(nums): - res ^= i - res ^= num - res ^= len(nums) - return res diff --git a/leetcode/lcci/src.main/java/17.12.BiNode/README_EN.md b/leetcode/lcci/src.main/java/17.12.BiNode/README_EN.md deleted file mode 100644 index 14d8a7f6..00000000 --- a/leetcode/lcci/src.main/java/17.12.BiNode/README_EN.md +++ /dev/null @@ -1,107 +0,0 @@ -# [17.12. BiNode](https://leetcode-cn.com/problems/binode-lcci) - -[中文文档](/lcci/17.12.BiNode/README.md) - -## Description - -
The data structure TreeNode
is used for binary tree, but it can also used to represent a single linked list (where left is null, and right is the next node in the list). Implement a method to convert a binary search tree (implemented with TreeNode
) into a single linked list. The values should be kept in order and the operation should be performed in place (that is, on the original data structure).
Return the head node of the linked list after converting.
- -Note: This problem is slightly different from the original one in the book.
- -- -
Example:
- -- -Input: [4,2,5,1,3,null,6,0] - -Output: [0,null,1,null,2,null,3,null,4,null,5,null,6] - -- -
Note:
- -Oh, no! You have accidentally removed all spaces, punctuation, and capitalization in a lengthy document. A sentence like "I reset the computer. It still didn't boot!" became "iresetthecomputeritstilldidntboot''. You'll deal with the punctuation and capitalization later; right now you need to re-insert the spaces. Most of the words are in a dictionary but a few are not. Given a dictionary (a list of strings) and the document (a string), design an algorithm to unconcatenate the document in a way that minimizes the number of unrecognized characters. Return the number of unrecognized characters.
- -Note: This problem is slightly different from the original one in the book.
- -- -
Example:
- -- -Input: - -dictionary = ["looked","just","like","her","brother"] - -sentence = "jesslookedjustliketimherbrother" - -Output: 7 - -Explanation: After unconcatenating, we got "jess looked just like tim her brother", which containing 7 unrecognized characters. - -- -
Note:
- -0 <= len(sentence) <= 1000
The total number of characters in dictionary
is less than or equal to 150000.dictionary
and sentence
.A popular masseuse receives a sequence of back-to-back appointment requests and is debating which ones to accept. She needs a break between appointments and therefore she cannot accept any adjacent requests. Given a sequence of back-to-back appoint ment requests, find the optimal (highest total booked minutes) set the masseuse can honor. Return the number of minutes.
- -Note: This problem is slightly different from the original one in the book.
- -- -
Example 1:
- -- -Input: [1,2,3,1] - -Output: 4 - -Explanation: Accept request 1 and 3, total minutes = 1 + 3 = 4 - -- -
Example 2:
- -- -Input: [2,7,9,3,1] - -Output: 12 - -Explanation: Accept request 1, 3 and 5, total minutes = 2 + 9 + 1 = 12 - -- -
Example 3:
- -- -Input: [2,1,4,5,3,1,1,3] - -Output: 12 - -Explanation: Accept request 1, 3, 5 and 8, total minutes = 2 + 4 + 3 + 3 = 12 - -- -## Solutions - - - -### **Python3** - -```python -class Solution: - def massage(self, nums: List[int]) -> int: - if not nums: - return 0 - n = len(nums) - if n < 2: - return nums[0] - a, b = nums[0], max(nums[0], nums[1]) - res = b - for i in range(2, n): - res = max(a + nums[i], b) - a, b = b, res - return res -``` - -### **Java** - -```java -package src.main.java; -import java.util.*; - -public class Solution { - public int massage(int[] nums) { - if (nums == null) { - return 0; - } - int n = nums.length; - if (n < 2) { - return n == 0 ? 0 : nums[0]; - } - int a = nums[0], b = Math.max(nums[0], nums[1]); - int res = b; - for (int i = 2; i < n; ++i) { - res = Math.max(a + nums[i], b); - a = b; - b = res; - } - return res; - } -} -``` - -### **...** - -``` - -``` - - diff --git a/leetcode/lcci/src.main/java/17.16.The Masseuse/Solution.py b/leetcode/lcci/src.main/java/17.16.The Masseuse/Solution.py deleted file mode 100644 index 869bdef3..00000000 --- a/leetcode/lcci/src.main/java/17.16.The Masseuse/Solution.py +++ /dev/null @@ -1,13 +0,0 @@ -class Solution: - def massage(self, nums: List[int]) -> int: - if not nums: - return 0 - n = len(nums) - if n < 2: - return nums[0] - a, b = nums[0], max(nums[0], nums[1]) - res = b - for i in range(2, n): - res = max(a + nums[i], b) - a, b = b, res - return res \ No newline at end of file diff --git a/leetcode/lcci/src.main/java/17.19.Missing Two/README_EN.md b/leetcode/lcci/src.main/java/17.19.Missing Two/README_EN.md deleted file mode 100644 index 7a4ffb85..00000000 --- a/leetcode/lcci/src.main/java/17.19.Missing Two/README_EN.md +++ /dev/null @@ -1,120 +0,0 @@ -# [17.19. Missing Two](https://leetcode-cn.com/problems/missing-two-lcci) - -[中文文档](/lcci/17.19.Missing%20Two/README.md) - -## Description - -
You are given an array with all the numbers from 1 to N appearing exactly once, except for two number that is missing. How can you find the missing number in O(N) time and 0(1) space?
- -You can return the missing numbers in any order.
- -Example 1:
- -
-
-Input: [1]
-
-Output: [2,3]
-
-Example 2:
- -
-
-Input: [2,3]
-
-Output: [1,4]
-
-Note:
- -nums.length <= 30000
Numbers are randomly generated and passed to a method. Write a program to find and maintain the median value as new values are generated.
- -Median is the middle value in an ordered integer list. If the size of the list is even, there is no middle value. So the median is the mean of the two middle value.
- -For example,
- -[2,3,4], the median is 3
- -[2,3], the median is (2 + 3) / 2 = 2.5
- -Design a data structure that supports the following two operations:
- -Example:
- -- -addNum(1) - -addNum(2) - -findMedian() -> 1.5 - -addNum(3) - -findMedian() -> 2 - -- -## Solutions - - - -### **Python3** - -```python -class MedianFinder: - - def __init__(self): - """ - initialize your data structure here. - """ - self.max_heap = [] - self.min_heap = [] - - - def addNum(self, num: int) -> None: - if len(self.max_heap) == len(self.min_heap): - heapq.heappush(self.min_heap, -heapq.heappushpop(self.max_heap, -num)) - else: - heapq.heappush(self.max_heap, -heapq.heappushpop(self.min_heap, num)) - - def findMedian(self) -> float: - return (-self.max_heap[0] + self.min_heap[0]) / 2 if len(self.max_heap) == len(self.min_heap) else self.min_heap[0] - - -# Your MedianFinder object will be instantiated and called as such: -# obj = MedianFinder() -# obj.addNum(num) -# param_2 = obj.findMedian() -``` - -### **Java** - -```java -class MedianFinder { - private Queue
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
- -You may assume that each input would have exactly one solution, and you may not use the same element twice.
- -Example:
- -- -Given nums = [2, 7, 11, 15], target = 9, - - - -Because nums[0] + nums[1] = 2 + 7 = 9, - -return [0, 1]. - -- -## Solutions - - - -### **Python3** - -```python -class Solution: - def twoSum(self, nums: List[int], target: int) -> List[int]: - helper = {} - for i, v in enumerate(nums): - num = target - v - if num in helper: - return [helper[num], i] - helper[v] = i -``` - -### **Java** - -```java -class Solution { - public int[] twoSum(int[] nums, int target) { - Map
You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
- -You may assume the two numbers do not contain any leading zero, except the number 0 itself.
- -Example:
- -- -Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) - -Output: 7 -> 0 -> 8 - -Explanation: 342 + 465 = 807. - -- -## Solutions - - - -### **Python3** - -```python -# Definition for singly-linked list. -# class ListNode: -# def __init__(self, val=0, next=None): -# self.val = val -# self.next = next -class Solution: - def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: - carry = 0 - dummy = ListNode(-1) - cur = dummy - while l1 or l2 or carry: - t = (0 if not l1 else l1.val) + (0 if not l2 else l2.val) + carry - carry = t // 10 - cur.next = ListNode(t % 10) - cur = cur.next - l1 = None if not l1 else l1.next - l2 = None if not l2 else l2.next - return dummy.next -``` - -### **Java** - -```java -/** - * Definition for singly-linked list. - * public class ListNode { - * int val; - * ListNode next; - * ListNode() {} - * ListNode(int val) { this.val = val; } - * ListNode(int val, ListNode next) { this.val = val; this.next = next; } - * } - */ -class Solution { - public ListNode addTwoNumbers(ListNode l1, ListNode l2) { - int carry = 0; - ListNode dummy = new ListNode(-1); - ListNode cur = dummy; - while (l1 != null || l2 != null || carry != 0) { - int t = (l1 == null ? 0 : l1.val) + (l2 == null ? 0 : l2.val) + carry; - carry = t / 10; - cur.next = new ListNode(t % 10); - cur = cur.next; - l1 = l1 == null ? null : l1.next; - l2 = l2 == null ? null : l2.next; - } - return dummy.next; - } -} -``` - -### **C#** - -```cs -/** - * Definition for singly-linked list. - * public class ListNode { - * public int val; - * public ListNode next; - * public ListNode(int val=0, ListNode next=null) { - * this.val = val; - * this.next = next; - * } - * } - */ -import java.util.*; - -public class Solution { - public ListNode AddTwoNumbers(ListNode l1, ListNode l2) { - ListNode dummy = new ListNode(-1); - ListNode cur = dummy; - var carry = 0; - while (l1 != null || l2 != null || carry != 0) - { - int t = (l1 == null ? 0 : l1.val) + (l2 == null ? 0 : l2.val) + carry; - carry = t / 10; - cur.next = new ListNode(t % 10); - cur = cur.next; - l1 = l1 == null ? null : l1.next; - l2 = l2 == null ? null : l2.next; - } - return dummy.next; - } -} -``` - -### **...** - -``` - -``` - - diff --git a/leetcode/solution/0000-0099/0002.Add Two Numbers/Solution.cpp b/leetcode/solution/0000-0099/0002.Add Two Numbers/Solution.cpp deleted file mode 100644 index fc01eaeb..00000000 --- a/leetcode/solution/0000-0099/0002.Add Two Numbers/Solution.cpp +++ /dev/null @@ -1,37 +0,0 @@ -class Solution { -public: - ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { - - ListNode *ans_l = new ListNode(0); - ListNode *head = ans_l; - int tmp = 0; - while(l1 != NULL && l2 != NULL){ - tmp += l1->val + l2->val; - ans_l->next = new ListNode(tmp % 10); - tmp = tmp / 10; - ans_l = ans_l->next; - l1 = l1->next; - l2 = l2->next; - } - - while(l1 != NULL){ - tmp += l1->val; - ans_l->next = new ListNode(tmp % 10); - tmp = tmp / 10; - ans_l = ans_l->next; - l1 = l1->next; - } - - while(l2 != NULL){ - tmp += l2->val; - ans_l->next = new ListNode(tmp % 10); - tmp = tmp / 10; - ans_l = ans_l->next; - l2 = l2->next; - } - - if(tmp)ans_l->next = new ListNode(tmp); - - return head->next; - } -}; diff --git a/leetcode/solution/0000-0099/0002.Add Two Numbers/Solution.cs b/leetcode/solution/0000-0099/0002.Add Two Numbers/Solution.cs deleted file mode 100644 index 7dc59ab7..00000000 --- a/leetcode/solution/0000-0099/0002.Add Two Numbers/Solution.cs +++ /dev/null @@ -1,30 +0,0 @@ -/** - * Definition for singly-linked list. - * public class ListNode { - * public int val; - * public ListNode next; - * public ListNode(int val=0, ListNode next=null) { - * this.val = val; - * this.next = next; - * } - * } - */ -import java.util.*; - -public class Solution { - public ListNode AddTwoNumbers(ListNode l1, ListNode l2) { - ListNode dummy = new ListNode(-1); - ListNode cur = dummy; - var carry = 0; - while (l1 != null || l2 != null || carry != 0) - { - int t = (l1 == null ? 0 : l1.val) + (l2 == null ? 0 : l2.val) + carry; - carry = t / 10; - cur.next = new ListNode(t % 10); - cur = cur.next; - l1 = l1 == null ? null : l1.next; - l2 = l2 == null ? null : l2.next; - } - return dummy.next; - } -} \ No newline at end of file diff --git a/leetcode/solution/0000-0099/0002.Add Two Numbers/Solution.go b/leetcode/solution/0000-0099/0002.Add Two Numbers/Solution.go deleted file mode 100644 index b1277fa6..00000000 --- a/leetcode/solution/0000-0099/0002.Add Two Numbers/Solution.go +++ /dev/null @@ -1,53 +0,0 @@ -/** - * Definition for singly-linked list. - * type ListNode struct { - * Val int - * Next *ListNode - * } - * - * Report by leetcode.com - * Runtime: 12 ms, Memory Usage: 5 MB - */ -func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode { - head := &ListNode{} - currentNode1 := l1 - currentNode2 := l2 - currentHead := head - sum := 0 - nextSum := 0 - - for true { - if currentNode1 != nil || currentNode2 != nil { - if currentNode1 == nil { - sum = nextSum + currentNode2.Val - nextSum = sum / 10 - currentNode2 = currentNode2.Next - } else if currentNode2 == nil { - sum = nextSum + currentNode1.Val - nextSum = sum / 10 - currentNode1 = currentNode1.Next - } else { - sum = nextSum + currentNode1.Val + currentNode2.Val - nextSum = sum / 10 - currentNode1 = currentNode1.Next - currentNode2 = currentNode2.Next - } - currentHead.Val = sum % 10 - // If there are elements present in the nodes then - // make a new node for future addition otherwise we - // will get unnecessary (0 -->
Given a string, find the length of the longest substring without repeating characters.
- -Example 1:
- -
-
-Input: "abcabcbb"
-
-Output: 3
-
-Explanation: The answer is "abc"
, with the length of 3.
-
-
-
-Example 2:
- -
-
-Input: "bbbbb"
-
-Output: 1
-
-Explanation: The answer is "b"
, with the length of 1.
-
-
-
-Example 3:
- -- -Input: "pwwkew" - -Output: 3 - -Explanation: The answer is- -"wke"
, with the length of 3. - - Note that the answer must be a substring,"pwke"
is a subsequence and not a substring. - -
There are two sorted arrays nums1 and nums2 of size m and n respectively.
- -Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).
- -You may assume nums1 and nums2 cannot be both empty.
- -Example 1:
- -- -nums1 = [1, 3] - -nums2 = [2] - - - -The median is 2.0 - -- -
Example 2:
- -- -nums1 = [1, 2] - -nums2 = [3, 4] - - - -The median is (2 + 3)/2 = 2.5 - -- -## Solutions - - - -### **Python3** - -```python - -``` - -### **Java** - -```java - -``` - -### **...** - -``` - -``` - - diff --git a/leetcode/solution/0000-0099/0004.Median of Two Sorted Arrays/Solution.cpp b/leetcode/solution/0000-0099/0004.Median of Two Sorted Arrays/Solution.cpp deleted file mode 100644 index 2496313f..00000000 --- a/leetcode/solution/0000-0099/0004.Median of Two Sorted Arrays/Solution.cpp +++ /dev/null @@ -1,36 +0,0 @@ -class Solution { -public: - double findMedianSortedArrays(vector
Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
- -Example 1:
- -- -Input: "babad" - -Output: "bab" - -Note: "aba" is also a valid answer. - -- -
Example 2:
- -- -Input: "cbbd" - -Output: "bb" - -- -## Solutions - - - -### **Python3** - -```python - -``` - -### **Java** - -```java - -``` - -### **...** - -``` - -``` - - diff --git a/leetcode/solution/0000-0099/0005.Longest Palindromic Substring/Solution.cs b/leetcode/solution/0000-0099/0005.Longest Palindromic Substring/Solution.cs deleted file mode 100644 index a19aa29d..00000000 --- a/leetcode/solution/0000-0099/0005.Longest Palindromic Substring/Solution.cs +++ /dev/null @@ -1,33 +0,0 @@ -import java.util.*; - -public class Solution { - public string LongestPalindrome(string s) { - var f = new bool[s.Length]; - var maxLen = 0; - var index = 0; - for (var p = 0; p <= 1; ++p) - { - for (var l = 1 + p; l <= s.Length; l += 2) - { - for (var i = 0; i <= s.Length - l; ++i) - { - if (l <= 2) - { - f[i] = s[i] == s[i + l - 1]; - } - else - { - f[i] = f[i + 1] && s[i] == s[i + l - 1]; - } - if (f[i] && l > maxLen) - { - maxLen = l; - index = i; - } - } - } - } - - return s.Substring(index, maxLen); - } -} \ No newline at end of file diff --git a/leetcode/solution/0000-0099/0005.Longest Palindromic Substring/Solution.go b/leetcode/solution/0000-0099/0005.Longest Palindromic Substring/Solution.go deleted file mode 100644 index dd27eaa3..00000000 --- a/leetcode/solution/0000-0099/0005.Longest Palindromic Substring/Solution.go +++ /dev/null @@ -1,28 +0,0 @@ -func longestPalindrome(s string) string { - length := len(s) - if length == 0 { - return "" - } - res := make([][]bool, length) - for i := 0; i < length; i++ { - res[i] = make([]bool, length) - } - max := 1 - start := 0 - for i := 0; i < length; i++ { - for j := 0; j <= i; j++ { - if i - j < 2 { - res[j][i] = s[j] == s[i] - } else { - res[j][i] = s[j] == s[i] && res[j+1][i-1] - } - - if res[j][i] && max < i - j + 1 { - max = i - j + 1 - start = j - } - } - } - - return s[start:start + max] -} \ No newline at end of file diff --git a/leetcode/solution/0000-0099/0005.Longest Palindromic Substring/Solution.js b/leetcode/solution/0000-0099/0005.Longest Palindromic Substring/Solution.js deleted file mode 100644 index 9a77a283..00000000 --- a/leetcode/solution/0000-0099/0005.Longest Palindromic Substring/Solution.js +++ /dev/null @@ -1,38 +0,0 @@ -/** - * @param {string} s - * @return {string} - */ -var longestPalindrome = function (s) { - let maxLength = 0, - left = 0, - right = 0; - for (let i = 0; i < s.length; i++) { - let singleCharLength = getPalLenByCenterChar(s, i, i); - let doubleCharLength = getPalLenByCenterChar(s, i, i + 1); - let max = Math.max(singleCharLength, doubleCharLength); - if (max > maxLength) { - maxLength = max; - left = i - parseInt((max - 1) / 2); - right = i + parseInt(max / 2); - } - } - return s.slice(left, right + 1); -}; - -function getPalLenByCenterChar(s, left, right) { - // 中间值为两个字符,确保两个字符相等 - if (s[left] != s[right]) { - return right - left; // 不相等返回为1个字符串 - } - while (left > 0 && right < s.length - 1) { - // 先加减再判断 - left--; - right++; - if (s[left] != s[right]) { - return right - left - 1; - } - } - return right - left + 1; -} - -console.log(longestPalindrome("cbbd")); diff --git a/leetcode/solution/0000-0099/0005.Longest Palindromic Substring/Solution.py b/leetcode/solution/0000-0099/0005.Longest Palindromic Substring/Solution.py deleted file mode 100644 index feee8060..00000000 --- a/leetcode/solution/0000-0099/0005.Longest Palindromic Substring/Solution.py +++ /dev/null @@ -1,24 +0,0 @@ -class Solution: - def longestPalindrome(self, s: str) -> str: - dp = [[0 for _ in range(len(s) + 1)] for _ in range(len(s) + 1)] - - for i in range(len(s)): - dp[i][i] = 1 - - for i in range(len(s) - 1, -1, -1): - for j in range(i + 1, len(s)): - if s[i] == s[j]: - if i + 1 == j: - dp[i][j] = 2 - elif i + 2 == j: - dp[i][j] = 3 - else: - if dp[i + 1][j - 1] != 0: - dp[i][j] = 2 + dp[i + 1][j - 1] - maximum = max(map(max, dp)) - if maximum == 0: - return "" - for i in range(len(s)): - for j in range(len(s)): - if dp[i][j] == maximum: - return s[i: j + 1] diff --git a/leetcode/solution/0000-0099/0006.ZigZag Conversion/README_EN.md b/leetcode/solution/0000-0099/0006.ZigZag Conversion/README_EN.md deleted file mode 100644 index 3a10fcad..00000000 --- a/leetcode/solution/0000-0099/0006.ZigZag Conversion/README_EN.md +++ /dev/null @@ -1,79 +0,0 @@ -# [6. ZigZag Conversion](https://leetcode.com/problems/zigzag-conversion) - -[中文文档](/solution/0000-0099/0006.ZigZag%20Conversion/README.md) - -## Description - -
The string "PAYPALISHIRING"
is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)
- -P A H N - -A P L S I I G - -Y I R - -- -
And then read line by line: "PAHNAPLSIIGYIR"
Write the code that will take a string and make this conversion given a number of rows:
- -- -string convert(string s, int numRows);- -
Example 1:
- -- -Input: s = "PAYPALISHIRING", numRows = 3 - -Output: "PAHNAPLSIIGYIR" - -- -
Example 2:
- -- -Input: s = "PAYPALISHIRING", numRows = 4 - -Output: "PINALSIGYAHRPI" - -Explanation: - - - -P I N - -A L S I G - -Y A H R - -P I- -## Solutions - - - -### **Python3** - -```python - -``` - -### **Java** - -```java - -``` - -### **...** - -``` - -``` - - diff --git a/leetcode/solution/0000-0099/0006.ZigZag Conversion/Solution.cpp b/leetcode/solution/0000-0099/0006.ZigZag Conversion/Solution.cpp deleted file mode 100644 index 44d9edaa..00000000 --- a/leetcode/solution/0000-0099/0006.ZigZag Conversion/Solution.cpp +++ /dev/null @@ -1,36 +0,0 @@ -// @ID:6. ZigZag Conversion -// @author:jxdeng3989 - -class Solution { -public: - string convert(string s, int numRows) { - string retstr; - if(1==numRows) - return s; - for(int i=0; i
Given a 32-bit signed integer, reverse digits of an integer.
- -Example 1:
- -- -Input: 123 - -Output: 321 - -- -
Example 2:
- -- -Input: -123 - -Output: -321 - -- -
Example 3:
- -- -Input: 120 - -Output: 21 - -- -
Note:
-
-Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
Implement atoi
which converts a string to an integer.
The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.
- -The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.
- -If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.
- -If no valid conversion could be performed, a zero value is returned.
- -Note:
- -' '
is considered as whitespace character.Example 1:
- -- -Input: "42" - -Output: 42 - -- -
Example 2:
- -- -Input: " -42" - -Output: -42 - -Explanation: The first non-whitespace character is '-', which is the minus sign. - - Then take as many numerical digits as possible, which gets 42. - -- -
Example 3:
- -- -Input: "4193 with words" - -Output: 4193 - -Explanation: Conversion stops at digit '3' as the next character is not a numerical digit. - -- -
Example 4:
- -- -Input: "words and 987" - -Output: 0 - -Explanation: The first non-whitespace character is 'w', which is not a numerical - - digit or a +/- sign. Therefore no valid conversion could be performed.- -
Example 5:
- -- -Input: "-91283472332" - -Output: -2147483648 - -Explanation: The number "-91283472332" is out of the range of a 32-bit signed integer. - - Thefore INT_MIN (−231) is returned.- -## Solutions - - - -### **Python3** - -```python -class Solution: - def myAtoi(self, s: str) -> int: - if not s: - return 0 - n = len(s) - if n == 0: - return 0 - i = 0 - while s[i] == ' ': - i += 1 - # only contains blank space - if i == n: - return 0 - sign = -1 if s[i] == '-' else 1 - if s[i] in ['-', '+']: - i += 1 - res, flag = 0, (2 ** 31 - 1) // 10 - while i < n: - # not a number, exit the loop - if not s[i].isdigit(): - break - c = int(s[i]) - # if overflows - if res > flag or (res == flag and c > 7): - return 2 ** 31 - 1 if sign > 0 else -2 ** 31 - res = res * 10 + c - i += 1 - return sign * res -``` - -### **Java** - -```java -class Solution { - public int myAtoi(String s) { - if (s == null) return 0; - int n = s.length(); - if (n == 0) return 0; - int i = 0; - while (s.charAt(i) == ' ') { - // only contains blank space - if (++i == n) return 0; - } - int sign = 1; - if (s.charAt(i) == '-') sign = -1; - if (s.charAt(i) == '-' || s.charAt(i) == '+') ++i; - int res = 0, flag = Integer.MAX_VALUE / 10; - for (; i < n; ++i) { - // not a number, exit the loop - if (s.charAt(i) < '0' || s.charAt(i) > '9') break; - // if overflows - if (res > flag || (res == flag && s.charAt(i) > '7')) return sign > 0 ? Integer.MAX_VALUE : Integer.MIN_VALUE; - res = res * 10 + (s.charAt(i) - '0'); - } - return sign * res; - } -} -``` - -### **...** - -``` - -``` - - diff --git a/leetcode/solution/0000-0099/0008.String to Integer (atoi)/Solution.cs b/leetcode/solution/0000-0099/0008.String to Integer (atoi)/Solution.cs deleted file mode 100644 index dc30aefb..00000000 --- a/leetcode/solution/0000-0099/0008.String to Integer (atoi)/Solution.cs +++ /dev/null @@ -1,46 +0,0 @@ -// https://leetcode.com/problems/string-to-integer-atoi/ - -public partial class Solution -{ - public int MyAtoi(string str) - { - int i = 0; - long result = 0; - bool minus = false; - while (i < str.Length && char.IsWhiteSpace(str[i])) - { - ++i; - } - if (i < str.Length) - { - if (str[i] == '+') - { - ++i; - } - else if (str[i] == '-') - { - minus = true; - ++i; - } - } - while (i < str.Length && char.IsDigit(str[i])) - { - result = result * 10 + str[i] - '0'; - if (result > int.MaxValue) - { - break; - } - ++i; - } - if (minus) result = -result; - if (result > int.MaxValue) - { - result = int.MaxValue; - } - if (result < int.MinValue) - { - result = int.MinValue; - } - return (int)result; - } -} \ No newline at end of file diff --git a/leetcode/solution/0000-0099/0008.String to Integer (atoi)/Solution.go b/leetcode/solution/0000-0099/0008.String to Integer (atoi)/Solution.go deleted file mode 100644 index 230cf220..00000000 --- a/leetcode/solution/0000-0099/0008.String to Integer (atoi)/Solution.go +++ /dev/null @@ -1,37 +0,0 @@ -func myAtoi(str string) int { - cer := 0 - result := 0 - tmpResult := 0 - flag := false - for _, n := range str { - if !flag && n == ' ' { - continue - } - flag = true - if cer == 0 { - if n >= '0' && n <= '9' { - cer = 1 - } else if n == '+' { - cer = 1 - continue - } else if cer == 0 && (n == '-') { - cer = -1 - continue - } - } - - if n >= '0' && n <= '9' { - tmpResult = tmpResult * 10 + ((int)(n) - 48) - result = cer * tmpResult - } else { - break - } - if result < math.MinInt32 { - return math.MinInt32 - } - if result > math.MaxInt32 { - return math.MaxInt32 - } - } - return result -} \ No newline at end of file diff --git a/leetcode/solution/0000-0099/0008.String to Integer (atoi)/Solution.js b/leetcode/solution/0000-0099/0008.String to Integer (atoi)/Solution.js deleted file mode 100644 index e73b6cd7..00000000 --- a/leetcode/solution/0000-0099/0008.String to Integer (atoi)/Solution.js +++ /dev/null @@ -1,24 +0,0 @@ -const myAtoi = function (str) { - str = str.trim(); - if (!str) return 0; - let isPositive = 1; - let i = 0, - ans = 0; - if (str[i] === "+") { - isPositive = 1; - i++; - } else if (str[i] === "-") { - isPositive = 0; - i++; - } - for (; i < str.length; i++) { - let t = str.charCodeAt(i) - 48; - if (t > 9 || t < 0) break; - if (ans > 2147483647 / 10 || ans > (2147483647 - t) / 10) { - return isPositive ? 2147483647 : -2147483648; - } else { - ans = ans * 10 + t; - } - } - return isPositive ? ans : -ans; -}; diff --git a/leetcode/solution/0000-0099/0008.String to Integer (atoi)/Solution.py b/leetcode/solution/0000-0099/0008.String to Integer (atoi)/Solution.py deleted file mode 100644 index 42a02ff9..00000000 --- a/leetcode/solution/0000-0099/0008.String to Integer (atoi)/Solution.py +++ /dev/null @@ -1,28 +0,0 @@ -class Solution: - def myAtoi(self, s: str) -> int: - if not s: - return 0 - n = len(s) - if n == 0: - return 0 - i = 0 - while s[i] == ' ': - i += 1 - # only contains blank space - if i == n: - return 0 - sign = -1 if s[i] == '-' else 1 - if s[i] in ['-', '+']: - i += 1 - res, flag = 0, (2 ** 31 - 1) // 10 - while i < n: - # not a number, exit the loop - if not s[i].isdigit(): - break - c = int(s[i]) - # if overflows - if res > flag or (res == flag and c > 7): - return 2 ** 31 - 1 if sign > 0 else -2 ** 31 - res = res * 10 + c - i += 1 - return sign * res diff --git a/leetcode/solution/0000-0099/0009.Palindrome Number/README_EN.md b/leetcode/solution/0000-0099/0009.Palindrome Number/README_EN.md deleted file mode 100644 index 4c7a2094..00000000 --- a/leetcode/solution/0000-0099/0009.Palindrome Number/README_EN.md +++ /dev/null @@ -1,87 +0,0 @@ -# [9. Palindrome Number](https://leetcode.com/problems/palindrome-number) - -[中文文档](/solution/0000-0099/0009.Palindrome%20Number/README.md) - -## Description - -
Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.
- -Example 1:
- -- -Input: 121 - -Output: true - -- -
Example 2:
- -- -Input: -121 - -Output: false - -Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome. - -- -
Example 3:
- -- -Input: 10 - -Output: false - -Explanation: Reads 01 from right to left. Therefore it is not a palindrome. - -- -
Follow up:
- -Coud you solve it without converting the integer to a string?
- -## Solutions - - - -### **Python3** - -```python -class Solution: - def isPalindrome(self, x: int) -> bool: - if x < 0: - return False - y, t = 0, x - while t: - y = y * 10 + t % 10 - t //= 10 - return x == y -``` - -### **Java** - -```java -class Solution { - public boolean isPalindrome(int x) { - if (x < 0) return false; - int y = 0, t = x; - while (t != 0) { - y = y * 10 + t % 10; - t /= 10; - } - return x == y; - } -} -``` - -### **...** - -``` - -``` - - diff --git a/leetcode/solution/0000-0099/0009.Palindrome Number/Solution.go b/leetcode/solution/0000-0099/0009.Palindrome Number/Solution.go deleted file mode 100644 index 0520bf78..00000000 --- a/leetcode/solution/0000-0099/0009.Palindrome Number/Solution.go +++ /dev/null @@ -1,12 +0,0 @@ -func isPalindrome(x int) bool { - if x < 0 { - return false - } - result := 0 - y := x - for y != 0 { - result = result * 10 + y%10 - y /= 10 - } - return result == x -} \ No newline at end of file diff --git a/leetcode/solution/0000-0099/0009.Palindrome Number/Solution.js b/leetcode/solution/0000-0099/0009.Palindrome Number/Solution.js deleted file mode 100644 index 355cce79..00000000 --- a/leetcode/solution/0000-0099/0009.Palindrome Number/Solution.js +++ /dev/null @@ -1,15 +0,0 @@ -/** - * @param {number} x - * @return {boolean} - */ -var isPalindrome = function (x) { - let str = x + ""; - let left = 0, - right = str.length - 1; - while (left < right) { - if (str[left] != str[right]) return false; - left++; - right--; - } - return true; -}; diff --git a/leetcode/solution/0000-0099/0009.Palindrome Number/Solution.py b/leetcode/solution/0000-0099/0009.Palindrome Number/Solution.py deleted file mode 100644 index 20666fee..00000000 --- a/leetcode/solution/0000-0099/0009.Palindrome Number/Solution.py +++ /dev/null @@ -1,9 +0,0 @@ -class Solution: - def isPalindrome(self, x: int) -> bool: - if x < 0: - return False - y, t = 0, x - while t: - y = y * 10 + t % 10 - t //= 10 - return x == y diff --git a/leetcode/solution/0000-0099/0010.Regular Expression Matching/README_EN.md b/leetcode/solution/0000-0099/0010.Regular Expression Matching/README_EN.md deleted file mode 100644 index ee5191b4..00000000 --- a/leetcode/solution/0000-0099/0010.Regular Expression Matching/README_EN.md +++ /dev/null @@ -1,94 +0,0 @@ -# [10. Regular Expression Matching](https://leetcode.com/problems/regular-expression-matching) - -[中文文档](/solution/0000-0099/0010.Regular%20Expression%20Matching/README.md) - -## Description - -Given an input string (s
) and a pattern (p
), implement regular expression matching with support for '.'
and '*'
.
-'.' Matches any single character. -'*' Matches zero or more of the preceding element. -- -
The matching should cover the entire input string (not partial).
- -Note:
- -s
could be empty and contains only lowercase letters a-z
.p
could be empty and contains only lowercase letters a-z
, and characters like .
or *
.Example 1:
- --Input: -s = "aa" -p = "a" -Output: false -Explanation: "a" does not match the entire string "aa". -- -
Example 2:
- --Input: -s = "aa" -p = "a*" -Output: true -Explanation: '*' means zero or more of the preceding element, 'a'. Therefore, by repeating 'a' once, it becomes "aa". -- -
Example 3:
- --Input: -s = "ab" -p = ".*" -Output: true -Explanation: ".*" means "zero or more (*) of any character (.)". -- -
Example 4:
- --Input: -s = "aab" -p = "c*a*b" -Output: true -Explanation: c can be repeated 0 times, a can be repeated 1 time. Therefore, it matches "aab". -- -
Example 5:
- --Input: -s = "mississippi" -p = "mis*is*p*." -Output: false -- -## Solutions - - - -### **Python3** - -```python - -``` - -### **Java** - -```java - -``` - -### **...** - -``` - -``` - - diff --git a/leetcode/solution/0000-0099/0010.Regular Expression Matching/Solution.cs b/leetcode/solution/0000-0099/0010.Regular Expression Matching/Solution.cs deleted file mode 100644 index 028f87e5..00000000 --- a/leetcode/solution/0000-0099/0010.Regular Expression Matching/Solution.cs +++ /dev/null @@ -1,49 +0,0 @@ -import java.util.*; - -public class Solution { - public bool IsMatch(string s, string p) { - var f = new bool[s.Length + 1, p.Length + 1]; - f[0, 0] = true; - for (var i = 0; i <= s.Length; ++i) - { - for (var j = 0; j <= p.Length; ++j) - { - if (i != 0 || j != 0) - { - if (j == 0) - { - f[i, j] = false; - } - else if (i == 0) - { - if (p[j - 1] == '*') - { - f[i, j] = f[i, j - 2]; - } - else - { - f[i, j] = false; - } - } - else - { - if (p[j - 1] == '.') - { - f[i, j] = f[i - 1, j - 1]; - } - else if (p[j - 1] == '*') - { - f[i, j] = f[i - 1, j] && (s[i - 1] == p[j - 2] || p[j - 2] == '.') || f[i, j - 2]; - } - else - { - f[i, j] = f[i - 1, j - 1] && s[i - 1] == p[j - 1]; - } - } - } - } - } - - return f[s.Length, p.Length]; - } -} \ No newline at end of file diff --git a/leetcode/solution/0000-0099/0010.Regular Expression Matching/Solution.go b/leetcode/solution/0000-0099/0010.Regular Expression Matching/Solution.go deleted file mode 100644 index 559dfa39..00000000 --- a/leetcode/solution/0000-0099/0010.Regular Expression Matching/Solution.go +++ /dev/null @@ -1,15 +0,0 @@ -func isMatch(s string, p string) bool { - //p only contains `.` or `*` or `[a-z]` - lenP := len(p) - lenS := len(s) - if lenP == 0 { - return lenS == 0 - } - fm := lenS != 0 && (s[0] == p[0] || p[0] == '.') - - if len(p) >= 2 && p[1] == '*' { - return isMatch(s, p[2:]) || fm && isMatch(s[1:], p) - } else { - return fm && isMatch(s[1:], p[1:]) - } -} \ No newline at end of file diff --git a/leetcode/solution/0000-0099/0011.Container With Most Water/README_EN.md b/leetcode/solution/0000-0099/0011.Container With Most Water/README_EN.md deleted file mode 100644 index c7fc7a6f..00000000 --- a/leetcode/solution/0000-0099/0011.Container With Most Water/README_EN.md +++ /dev/null @@ -1,49 +0,0 @@ -# [11. Container With Most Water](https://leetcode.com/problems/container-with-most-water) - -[中文文档](/solution/0000-0099/0011.Container%20With%20Most%20Water/README.md) - -## Description - -
Given n non-negative integers a1, a2, ..., an , where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water.
- -Note: You may not slant the container and n is at least 2.
- -- - - -
The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49.
- -- -
Example:
- -- -Input: [1,8,6,2,5,4,8,3,7] - -Output: 49- -## Solutions - - - -### **Python3** - -```python - -``` - -### **Java** - -```java - -``` - -### **...** - -``` - -``` - - diff --git a/leetcode/solution/0000-0099/0011.Container With Most Water/Solution.cpp b/leetcode/solution/0000-0099/0011.Container With Most Water/Solution.cpp deleted file mode 100644 index 50d2b7b7..00000000 --- a/leetcode/solution/0000-0099/0011.Container With Most Water/Solution.cpp +++ /dev/null @@ -1,20 +0,0 @@ -class Solution { -public: - int maxArea(vector
Roman numerals are represented by seven different symbols: I
, V
, X
, L
, C
, D
and M
.
- -Symbol Value - -I 1 - -V 5 - -X 10 - -L 50 - -C 100 - -D 500 - -M 1000- -
For example, two is written as II
in Roman numeral, just two one's added together. Twelve is written as, XII
, which is simply X
+ II
. The number twenty seven is written as XXVII
, which is XX
+ V
+ II
.
Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII
. Instead, the number four is written as IV
. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX
. There are six instances where subtraction is used:
I
can be placed before V
(5) and X
(10) to make 4 and 9. X
can be placed before L
(50) and C
(100) to make 40 and 90. C
can be placed before D
(500) and M
(1000) to make 400 and 900.Given an integer, convert it to a roman numeral. Input is guaranteed to be within the range from 1 to 3999.
- -Example 1:
- -- -Input: 3 - -Output: "III"- -
Example 2:
- -- -Input: 4 - -Output: "IV"- -
Example 3:
- -- -Input: 9 - -Output: "IX"- -
Example 4:
- -- -Input: 58 - -Output: "LVIII" - -Explanation: L = 50, V = 5, III = 3. - -- -
Example 5:
- -- -Input: 1994 - -Output: "MCMXCIV" - -Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.- -## Solutions - - - -### **Python3** - -```python - -``` - -### **Java** - -```java - -``` - -### **...** - -``` - -``` - - diff --git a/leetcode/solution/0000-0099/0012.Integer to Roman/Solution.go b/leetcode/solution/0000-0099/0012.Integer to Roman/Solution.go deleted file mode 100644 index a08d8d64..00000000 --- a/leetcode/solution/0000-0099/0012.Integer to Roman/Solution.go +++ /dev/null @@ -1,49 +0,0 @@ -// 字符 数值 -// I 1 -// V 5 -// X 10 -// L 50 -// C 100 -// D 500 -// M 1000 -var table = make(map[int]string) -var keys = []int{1,4,5,9,10,40,50,90,100,400,500,900,1000} - -func init() { - table[1] = "I" - table[4] = "IV" - table[5] = "V" - table[9] = "IX" - table[10] = "X" - table[40] = "XL" - table[50] = "L" - table[90] = "XC" - table[100] = "C" - table[400] = "CD" - table[500] = "D" - table[900] = "CM" - table[1000] = "M" -} - -func intToRoman(num int) string { - if n, exist := table[num]; exist { - return n - } - var result string - lenKeys := len(keys) - for i:=lenKeys-1; i>=0; i-- { - d := keys[i] - count := num/d - result += genreateRoman(d, count) - num = num - d * count - } - return result -} - -func genreateRoman(n, count int) string { - var r string - for i:=0; i
I
, V
, X
, L
, C
, D
and M
.
-
-- -Symbol Value - -I 1 - -V 5 - -X 10 - -L 50 - -C 100 - -D 500 - -M 1000- -
For example, two is written as II
in Roman numeral, just two one's added together. Twelve is written as, XII
, which is simply X
+ II
. The number twenty seven is written as XXVII
, which is XX
+ V
+ II
.
Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII
. Instead, the number four is written as IV
. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX
. There are six instances where subtraction is used:
I
can be placed before V
(5) and X
(10) to make 4 and 9. X
can be placed before L
(50) and C
(100) to make 40 and 90. C
can be placed before D
(500) and M
(1000) to make 400 and 900.Given a roman numeral, convert it to an integer. Input is guaranteed to be within the range from 1 to 3999.
- -Example 1:
- -- -Input: "III" - -Output: 3- -
Example 2:
- -- -Input: "IV" - -Output: 4- -
Example 3:
- -- -Input: "IX" - -Output: 9- -
Example 4:
- -- -Input: "LVIII" - -Output: 58 - -Explanation: L = 50, V= 5, III = 3. - -- -
Example 5:
- -- -Input: "MCMXCIV" - -Output: 1994 - -Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.- -## Solutions - - - -### **Python3** - -```python - -``` - -### **Java** - -```java - -``` - -### **...** - -``` - -``` - - diff --git a/leetcode/solution/0000-0099/0013.Roman to Integer/Solution.go b/leetcode/solution/0000-0099/0013.Roman to Integer/Solution.go deleted file mode 100644 index 375e8ab2..00000000 --- a/leetcode/solution/0000-0099/0013.Roman to Integer/Solution.go +++ /dev/null @@ -1,41 +0,0 @@ -// 字符 数值 -// I 1 -// V 5 -// X 10 -// L 50 -// C 100 -// D 500 -// M 1000 -var table = make(map[string]int) - -func init() { - table["I"] = 1 - table["IV"] = 4 - table["V"] = 5 - table["IX"] = 9 - table["X"] = 10 - table["XL"] = 40 - table["L"] = 50 - table["XC"] = 90 - table["C"] = 100 - table["CD"] = 400 - table["D"] = 500 - table["CM"] = 900 - table["M"] = 1000 -} - -func romanToInt(s string) int { - var result int - lenS := len(s) - for i:=0; i
Write a function to find the longest common prefix string amongst an array of strings.
- -If there is no common prefix, return an empty string ""
.
Example 1:
- -- -Input: ["flower","flow","flight"] - -Output: "fl" - -- -
Example 2:
- -- -Input: ["dog","racecar","car"] - -Output: "" - -Explanation: There is no common prefix among the input strings. - -- -
Note:
- -All given inputs are in lowercase letters a-z
.
Given an array nums
of n integers, are there elements a, b, c in nums
such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
Note:
- -The solution set must not contain duplicate triplets.
- -Example:
- -- -Given array nums = [-1, 0, 1, 2, -1, -4], - - - -A solution set is: - -[ - - [-1, 0, 1], - - [-1, -1, 2] - -] - -- -## Solutions - - - -### **Python3** - -```python -class Solution: - def threeSum(self, nums: List[int]) -> List[List[int]]: - if nums is None or len(nums) < 3: - return [] - nums.sort() - n = len(nums) - res = [] - for i in range(n - 2): - if i > 0 and nums[i] == nums[i - 1]: - continue - p, q = i + 1, n - 1 - while p < q: - if p > i + 1 and nums[p] == nums[p - 1]: - p += 1 - continue - if q < n - 1 and nums[q] == nums[q + 1]: - q -= 1 - continue - if nums[i] + nums[p] + nums[q] < 0: - p += 1 - elif nums[i] + nums[p] + nums[q] > 0: - q -= 1 - else: - res.append([nums[i], nums[p], nums[q]]) - p += 1 - q -= 1 - return res -``` - -### **Java** - -```java -class Solution { - public List
Given an array nums
of n integers and an integer target
, find three integers in nums
such that the sum is closest to target
. Return the sum of the three integers. You may assume that each input would have exactly one solution.
Example:
- -- -Given array nums = [-1, 2, 1, -4], and target = 1. - - - -The sum that is closest to the target is 2. (-1 + 2 + 1 = 2). - -- -## Solutions - - - -### **Python3** - -```python - -``` - -### **Java** - -```java - -``` - -### **...** - -``` - -``` - - diff --git a/leetcode/solution/0000-0099/0016.3Sum Closest/Solution.go b/leetcode/solution/0000-0099/0016.3Sum Closest/Solution.go deleted file mode 100644 index a70c2440..00000000 --- a/leetcode/solution/0000-0099/0016.3Sum Closest/Solution.go +++ /dev/null @@ -1,54 +0,0 @@ -func threeSumClosest(nums []int, target int) int { - sort(nums) - lenNums := len(nums) - result := nums[0] + nums[1] + nums[2] - for i, n := range nums { - left := i + 1 - right := lenNums - 1 - for left < right { - r := nums[left] + nums[right] + n - if abs(r - target) < abs(result - target) { - result = r - } - if r > target { - right-- - } else if r < target { - left++ - } else { - return result - } - } - } - return result -} - -func abs(a int) int { - if a >= 0 { - return a - } - return -a; -} - -// quick sort -func sort(array []int) { - if len(array) == 0 { - return - } - left := 0 - right := len(array) - 1 - obj := array[left] - for left < right { - for left < right && array[right] >= obj { - right-- - } - array[left] = array[right] - - for left < right && array[left] <= obj { - left++ - } - array[right] = array[left] - } - array[left] = obj - sort(array[:left]) - sort(array[right+1:]) -} \ No newline at end of file diff --git a/leetcode/solution/0000-0099/0017.Letter Combinations of a Phone Number/README_EN.md b/leetcode/solution/0000-0099/0017.Letter Combinations of a Phone Number/README_EN.md deleted file mode 100644 index ff94318c..00000000 --- a/leetcode/solution/0000-0099/0017.Letter Combinations of a Phone Number/README_EN.md +++ /dev/null @@ -1,49 +0,0 @@ -# [17. Letter Combinations of a Phone Number](https://leetcode.com/problems/letter-combinations-of-a-phone-number) - -[中文文档](/solution/0000-0099/0017.Letter%20Combinations%20of%20a%20Phone%20Number/README.md) - -## Description - -
Given a string containing digits from 2-9
inclusive, return all possible letter combinations that the number could represent.
A mapping of digit to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.
- - - -Example:
- -- -Input: "23" - -Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"]. - -- -
Note:
- -Although the above answer is in lexicographical order, your answer could be in any order you want.
- -## Solutions - - - -### **Python3** - -```python - -``` - -### **Java** - -```java - -``` - -### **...** - -``` - -``` - - diff --git a/leetcode/solution/0000-0099/0017.Letter Combinations of a Phone Number/Solution.cs b/leetcode/solution/0000-0099/0017.Letter Combinations of a Phone Number/Solution.cs deleted file mode 100644 index 7d95edfc..00000000 --- a/leetcode/solution/0000-0099/0017.Letter Combinations of a Phone Number/Solution.cs +++ /dev/null @@ -1,39 +0,0 @@ -using System.Collections.Generic; -using System.Linq; - -import java.util.*; - -public class Solution { - private static string[] chars = { - "abc", - "def", - "ghi", - "jkl", - "mno", - "pqrs", - "tuv", - "wxyz" - }; - - public IListnums
of n integers and an integer target
, are there elements a, b, c, and d in nums
such that a + b + c + d = target
? Find all unique quadruplets in the array which gives the sum of target
.
-
-Note:
- -The solution set must not contain duplicate quadruplets.
- -Example:
- -- -Given array nums = [1, 0, -1, 0, -2, 2], and target = 0. - - - -A solution set is: - -[ - - [-1, 0, 0, 1], - - [-2, -1, 1, 2], - - [-2, 0, 0, 2] - -] - -- -## Solutions - - - -### **Python3** - -```python -class Solution: - def fourSum(self, nums: List[int], target: int) -> List[List[int]]: - res = [] - if nums is None or len(nums) < 4: - return res - n = len(nums) - nums.sort() - for i in range(n - 3): - if i > 0 and nums[i] == nums[i - 1]: - continue - for j in range(i + 1, n - 2): - if j > i + 1 and nums[j] == nums[j - 1]: - continue - p, q = j + 1, n - 1 - while p < q: - if p > j + 1 and nums[p] == nums[p - 1]: - p += 1 - continue - if q < n - 1 and nums[q] == nums[q + 1]: - q -= 1 - continue - t = nums[i] + nums[j] + nums[p] + nums[q] - if t == target: - res.append([nums[i], nums[j], nums[p], nums[q]]) - p += 1 - q -= 1 - elif t < target: - p += 1 - else: - q -= 1 - return res -``` - -### **Java** - -```java -class Solution { - public List
Given a linked list, remove the n-th node from the end of list and return its head.
- -Example:
- -- -Given linked list: 1->2->3->4->5, and n = 2. - - - -After removing the second node from the end, the linked list becomes 1->2->3->5. - -- -
Note:
- -Given n will always be valid.
- -Follow up:
- -Could you do this in one pass?
- -## Solutions - - - -### **Python3** - -```python -# Definition for singly-linked list. -# class ListNode: -# def __init__(self, val=0, next=None): -# self.val = val -# self.next = next -class Solution: - def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode: - dummy = ListNode(0, head) - p = q = dummy - for i in range(n): - p = p.next - while p.next is not None: - p = p.next - q = q.next - q.next = q.next.next - return dummy.next -``` - -### **Java** - -```java -/** - * Definition for singly-linked list. - * public class ListNode { - * int val; - * ListNode next; - * ListNode() {} - * ListNode(int val) { this.val = val; } - * ListNode(int val, ListNode next) { this.val = val; this.next = next; } - * } - */ -class Solution { - public ListNode removeNthFromEnd(ListNode head, int n) { - ListNode dummy = new ListNode(0, head); - ListNode p = dummy, q = dummy; - while (n-- > 0) { - p = p.next; - } - while (p.next != null) { - p = p.next; - q = q.next; - } - q.next = q.next.next; - return dummy.next; - } -} -``` - -### **...** - -``` - -``` - - diff --git a/leetcode/solution/0000-0099/0019.Remove Nth Node From End of List/Solution.cpp b/leetcode/solution/0000-0099/0019.Remove Nth Node From End of List/Solution.cpp deleted file mode 100644 index d9e9248e..00000000 --- a/leetcode/solution/0000-0099/0019.Remove Nth Node From End of List/Solution.cpp +++ /dev/null @@ -1,25 +0,0 @@ -class Solution { -public: - ListNode* removeNthFromEnd(ListNode* head, int n) { - ListNode *p, *q ; - q = head ; - p = head ; - - for (int i = 0; i < n; ++i) - q = q->next ; - - if (!q) - { - return head->next ; - } - - while (q->next) - { - q = q->next ; - p = p->next ; - } - - p->next = p->next->next ; - return head ; - } -}; \ No newline at end of file diff --git a/leetcode/solution/0000-0099/0019.Remove Nth Node From End of List/Solution.go b/leetcode/solution/0000-0099/0019.Remove Nth Node From End of List/Solution.go deleted file mode 100644 index 1f754b39..00000000 --- a/leetcode/solution/0000-0099/0019.Remove Nth Node From End of List/Solution.go +++ /dev/null @@ -1,23 +0,0 @@ -/** - * Definition for singly-linked list. - * type ListNode struct { - * Val int - * Next *ListNode - * } - */ - func removeNthFromEnd(head *ListNode, n int) *ListNode { - node0 := &ListNode{Val:0} - node0.Next = head - left := node0 - right := node0 - for n>0 { - right = right.Next - n-- - } - for right.Next != nil { - left = left.Next - right = right.Next - } - left.Next = left.Next.Next - return node0.Next -} \ No newline at end of file diff --git a/leetcode/solution/0000-0099/0019.Remove Nth Node From End of List/Solution.js b/leetcode/solution/0000-0099/0019.Remove Nth Node From End of List/Solution.js deleted file mode 100644 index cca2368b..00000000 --- a/leetcode/solution/0000-0099/0019.Remove Nth Node From End of List/Solution.js +++ /dev/null @@ -1,15 +0,0 @@ -const removeNthFromEnd = function (head, n) { - let left, - before, - right = head; - left = before = { next: head }; - while (n--) { - right = right.next; - } - while (right) { - right = right.next; - left = left.next; - } - left.next = left.next.next; - return before.next; -}; diff --git a/leetcode/solution/0000-0099/0019.Remove Nth Node From End of List/Solution.py b/leetcode/solution/0000-0099/0019.Remove Nth Node From End of List/Solution.py deleted file mode 100644 index 9666d7ab..00000000 --- a/leetcode/solution/0000-0099/0019.Remove Nth Node From End of List/Solution.py +++ /dev/null @@ -1,16 +0,0 @@ -# Definition for singly-linked list. -# class ListNode: -# def __init__(self, val=0, next=None): -# self.val = val -# self.next = next -class Solution: - def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode: - dummy = ListNode(0, head) - p = q = dummy - for i in range(n): - p = p.next - while p.next is not None: - p = p.next - q = q.next - q.next = q.next.next - return dummy.next \ No newline at end of file diff --git a/leetcode/solution/0000-0099/0019.Remove Nth Node From End of List/Solution.rb b/leetcode/solution/0000-0099/0019.Remove Nth Node From End of List/Solution.rb deleted file mode 100644 index 9654f08b..00000000 --- a/leetcode/solution/0000-0099/0019.Remove Nth Node From End of List/Solution.rb +++ /dev/null @@ -1,27 +0,0 @@ -# Definition for singly-linked list. -# class ListNode -# attr_accessor :val, :next -# def initialize(val) -# @val = val -# @next = nil -# end -# end - -# @param {ListNode} head -# @param {Integer} n -# @return {ListNode} -def remove_nth_from_end(head, n) - return nil if head.next.nil? - count = 1 - q = head - s = head - - while q.next do - q = q.next - s = s.next if count > n - count += 1 - end - return head.next if count == n - s.next = s.next.next - head -end diff --git a/leetcode/solution/0000-0099/0020.Valid Parentheses/README_EN.md b/leetcode/solution/0000-0099/0020.Valid Parentheses/README_EN.md deleted file mode 100644 index 14df331e..00000000 --- a/leetcode/solution/0000-0099/0020.Valid Parentheses/README_EN.md +++ /dev/null @@ -1,135 +0,0 @@ -# [20. Valid Parentheses](https://leetcode.com/problems/valid-parentheses) - -[中文文档](/solution/0000-0099/0020.Valid%20Parentheses/README.md) - -## Description - -Given a string containing just the characters '('
, ')'
, '{'
, '}'
, '['
and ']'
, determine if the input string is valid.
An input string is valid if:
- -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 - -- -## Solutions - - - -### **Python3** - -```python -class Solution: - def isValid(self, s: str) -> bool: - q = [] - parentheses = {'()', '[]', '{}'} - for ch in s: - if ch in '([{': - q.append(ch) - elif not q or q.pop() + ch not in parentheses: - return False - return not q -``` - -### **Java** - -```java -class Solution { - public boolean isValid(String s) { - char[] chars = s.toCharArray(); - Deque
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.
- -Example: - -
- -Input: 1->2->4, 1->3->4 - -Output: 1->1->2->3->4->4 - -- - - -## Solutions - - - -### **Python3** - -```python -# Definition for singly-linked list. -# class ListNode: -# def __init__(self, val=0, next=None): -# self.val = val -# self.next = next -class Solution: - def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: - dummy = ListNode() - cur = dummy - while l1 and l2: - if l1.val <= l2.val: - cur.next = l1 - l1 = l1.next - else: - cur.next = l2 - l2 = l2.next - cur = cur.next - cur.next = l1 or l2 - return dummy.next -``` - -### **Java** - -```java -/** - * Definition for singly-linked list. - * public class ListNode { - * int val; - * ListNode next; - * ListNode() {} - * ListNode(int val) { this.val = val; } - * ListNode(int val, ListNode next) { this.val = val; this.next = next; } - * } - */ -class Solution { - 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; - l1 = l1.next; - } else { - cur.next = l2; - l2 = l2.next; - } - cur = cur.next; - } - cur.next = l1 == null ? l2 : l1; - return dummy.next; - } -} -``` - -### **...** - -``` - -``` - - diff --git a/leetcode/solution/0000-0099/0021.Merge Two Sorted Lists/Solution.cpp b/leetcode/solution/0000-0099/0021.Merge Two Sorted Lists/Solution.cpp deleted file mode 100644 index 1f80f78c..00000000 --- a/leetcode/solution/0000-0099/0021.Merge Two Sorted Lists/Solution.cpp +++ /dev/null @@ -1,37 +0,0 @@ -/** - * 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 *a1=new ListNode(0); - ListNode *head=a1; - while(l1!=NULL&&l2!=NULL) - { - if(l1->val
- -Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. - -
- -- -For example, given n = 3, a solution set is: - -
- -- -[ - - "((()))", - - "(()())", - - "(())()", - - "()(())", - - "()()()" - -] - -- -## Solutions - - - -### **Python3** - -```python - -``` - -### **Java** - -```java - -``` - -### **...** - -``` - -``` - - diff --git a/leetcode/solution/0000-0099/0022.Generate Parentheses/Solution.go b/leetcode/solution/0000-0099/0022.Generate Parentheses/Solution.go deleted file mode 100644 index e087ab2c..00000000 --- a/leetcode/solution/0000-0099/0022.Generate Parentheses/Solution.go +++ /dev/null @@ -1,19 +0,0 @@ -func generateParenthesis(n int) []string { - result := make([]string, 0) - backParenthesis(&result, "", 0, 0, n) - return result -} - -func backParenthesis(result *[]string, cur string, open, close, max int) { - if len(cur) == 2 * max { - *result = append(*result, cur) - return - } - - if open < max { - backParenthesis(result, cur+"(", open+1, close, max) - } - if close < open { - backParenthesis(result, cur+")", open, close+1, max) - } -} \ No newline at end of file diff --git a/leetcode/solution/0000-0099/0023.Merge k Sorted Lists/README_EN.md b/leetcode/solution/0000-0099/0023.Merge k Sorted Lists/README_EN.md deleted file mode 100644 index 4da1986a..00000000 --- a/leetcode/solution/0000-0099/0023.Merge k Sorted Lists/README_EN.md +++ /dev/null @@ -1,116 +0,0 @@ -# [23. Merge k Sorted Lists](https://leetcode.com/problems/merge-k-sorted-lists) - -[中文文档](/solution/0000-0099/0023.Merge%20k%20Sorted%20Lists/README.md) - -## Description - -
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
- -Example:
- -- -Input: - -[ - - 1->4->5, - - 1->3->4, - - 2->6 - -] - -Output: 1->1->2->3->4->4->5->6 - -- -## Solutions - - - -### **Python3** - -```python -# Definition for singly-linked list. -# class ListNode: -# def __init__(self, val=0, next=None): -# self.val = val -# self.next = next -class Solution: - def mergeKLists(self, lists: List[ListNode]) -> ListNode: - if not lists: - return None - n = len(lists) - for i in range(1, n): - lists[i] = self.mergeTwoLists(lists[i - 1], lists[i]) - return lists[n - 1] - - - def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: - dummy = ListNode() - cur = dummy - while l1 and l2: - if l1.val <= l2.val: - cur.next = l1 - l1 = l1.next - else: - cur.next = l2 - l2 = l2.next - cur = cur.next - cur.next = l1 or l2 - return dummy.next -``` - -### **Java** - -```java -/** - * Definition for singly-linked list. - * public class ListNode { - * int val; - * ListNode next; - * ListNode() {} - * ListNode(int val) { this.val = val; } - * ListNode(int val, ListNode next) { this.val = val; this.next = next; } - * } - */ -class Solution { - public ListNode mergeKLists(ListNode[] lists) { - int n; - if (lists == null || (n = lists.length) == 0) { - return null; - } - for (int i = 1; i < n; ++i) { - lists[i] = mergeTwoLists(lists[i - 1], lists[i]); - } - return lists[n - 1]; - } - - private 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; - l1 = l1.next; - } else { - cur.next = l2; - l2 = l2.next; - } - cur = cur.next; - } - cur.next = l1 == null ? l2 : l1; - return dummy.next; - } -} -``` - -### **...** - -``` - -``` - - diff --git a/leetcode/solution/0000-0099/0023.Merge k Sorted Lists/Solution.cpp b/leetcode/solution/0000-0099/0023.Merge k Sorted Lists/Solution.cpp deleted file mode 100644 index 100de858..00000000 --- a/leetcode/solution/0000-0099/0023.Merge k Sorted Lists/Solution.cpp +++ /dev/null @@ -1,105 +0,0 @@ -class compare -{ -public: - bool operator()(ListNode *l1,ListNode *l2){ - //if(!l1 || !l2) - // return !l1; - - if(l1 == NULL)return 1; - if(l2 == NULL)return 0; - return l1->val > l2->val; - //这里比较的是优先级,默认优先级排序是“<”号,若 l1Val > l2Val 返回真,即表示l1优先级比l2小,l2先入队 - //队列的top()函数指的就是优先级最高的元素,即队头元素 - } -}; - - -class Solution{ -public: - ListNode* mergeKLists(vector
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- -## Solutions - - - -### **Python3** - -```python -# Definition for singly-linked list. -# class ListNode: -# def __init__(self, val=0, next=None): -# self.val = val -# self.next = next -class Solution: - def swapPairs(self, head: ListNode) -> ListNode: - dummy = ListNode(next=head) - pre, cur = dummy, head - while cur and cur.next: - t = cur.next - cur.next = t.next - t.next = cur - pre.next = t - pre = cur - cur = pre.next - return dummy.next -``` - -### **Java** - -```java -/** - * Definition for singly-linked list. - * public class ListNode { - * int val; - * ListNode next; - * ListNode() {} - * ListNode(int val) { this.val = val; } - * ListNode(int val, ListNode next) { this.val = val; this.next = next; } - * } - */ -class Solution { - public ListNode swapPairs(ListNode head) { - ListNode dummy = new ListNode(0, head); - ListNode pre = dummy, cur = head; - while (cur != null && cur.next != null) { - ListNode t = cur.next; - cur.next = t.next; - t.next = cur; - pre.next = t; - pre = cur; - cur = pre.next; - - } - return dummy.next; - } -} -``` - -### **C++** - -```cpp -/** - * Definition for singly-linked list. - * struct ListNode { - * int val; - * ListNode *next; - * ListNode() : val(0), next(nullptr) {} - * ListNode(int x) : val(x), next(nullptr) {} - * ListNode(int x, ListNode *next) : val(x), next(next) {} - * }; - */ -class Solution { -public: - ListNode* swapPairs(ListNode* head) { - ListNode* dummy = new ListNode(0, head); - ListNode* pre = dummy; - ListNode* cur = head; - while (cur != nullptr && cur->next != nullptr) { - ListNode* t = cur->next; - cur->next = t->next; - t->next = cur; - pre->next = t; - pre = cur; - cur = pre->next; - } - return dummy->next; - } -}; -``` - -### **...** - -``` - -``` - - diff --git a/leetcode/solution/0000-0099/0024.Swap Nodes in Pairs/Solution.cpp b/leetcode/solution/0000-0099/0024.Swap Nodes in Pairs/Solution.cpp deleted file mode 100644 index 7ec36020..00000000 --- a/leetcode/solution/0000-0099/0024.Swap Nodes in Pairs/Solution.cpp +++ /dev/null @@ -1,27 +0,0 @@ -/** - * Definition for singly-linked list. - * struct ListNode { - * int val; - * ListNode *next; - * ListNode() : val(0), next(nullptr) {} - * ListNode(int x) : val(x), next(nullptr) {} - * ListNode(int x, ListNode *next) : val(x), next(next) {} - * }; - */ -class Solution { -public: - ListNode* swapPairs(ListNode* head) { - ListNode* dummy = new ListNode(0, head); - ListNode* pre = dummy; - ListNode* cur = head; - while (cur != nullptr && cur->next != nullptr) { - ListNode* t = cur->next; - cur->next = t->next; - t->next = cur; - pre->next = t; - pre = cur; - cur = pre->next; - } - return dummy->next; - } -}; \ No newline at end of file diff --git a/leetcode/solution/0000-0099/0024.Swap Nodes in Pairs/Solution.go b/leetcode/solution/0000-0099/0024.Swap Nodes in Pairs/Solution.go deleted file mode 100644 index 48dde9d1..00000000 --- a/leetcode/solution/0000-0099/0024.Swap Nodes in Pairs/Solution.go +++ /dev/null @@ -1,32 +0,0 @@ -/** - * Definition for singly-linked list. - * type ListNode struct { - * Val int - * Next *ListNode - * } - */ - func swapPairs(head *ListNode) *ListNode { - if head == nil || head.Next == nil { - return head - } - first := head - second := head.Next - r := second - var p *ListNode = nil - for first != nil && second != nil { - t := second.Next - second.Next = first - first.Next = t - if p != nil { - p.Next = second - } - p = first - if t != nil { - second = t.Next - } else { - second = nil - } - first = t - } - return r -} \ No newline at end of file diff --git a/leetcode/solution/0000-0099/0024.Swap Nodes in Pairs/Solution.py b/leetcode/solution/0000-0099/0024.Swap Nodes in Pairs/Solution.py deleted file mode 100644 index 6811d2bc..00000000 --- a/leetcode/solution/0000-0099/0024.Swap Nodes in Pairs/Solution.py +++ /dev/null @@ -1,17 +0,0 @@ -# Definition for singly-linked list. -# class ListNode: -# def __init__(self, val=0, next=None): -# self.val = val -# self.next = next -class Solution: - def swapPairs(self, head: ListNode) -> ListNode: - dummy = ListNode(next=head) - pre, cur = dummy, head - while cur and cur.next: - t = cur.next - cur.next = t.next - t.next = cur - pre.next = t - pre = cur - cur = pre.next - return dummy.next diff --git a/leetcode/solution/0000-0099/0024.Swap Nodes in Pairs/Solution.rb b/leetcode/solution/0000-0099/0024.Swap Nodes in Pairs/Solution.rb deleted file mode 100644 index dd41bcfb..00000000 --- a/leetcode/solution/0000-0099/0024.Swap Nodes in Pairs/Solution.rb +++ /dev/null @@ -1,23 +0,0 @@ -# Definition for singly-linked list. -# class ListNode -# attr_accessor :val, :next -# def initialize(val) -# @val = val -# @next = nil -# end -# end - -# @param {ListNode} head -# @return {ListNode} -def swap_pairs(head) - if head.nil? || head.next.nil? - return head - end - - res = head.next - tmp = head.next.next - head.next.next = head - head.next = swap_pairs(tmp) - - res -end diff --git a/leetcode/solution/0000-0099/0025.Reverse Nodes in k-Group/README_EN.md b/leetcode/solution/0000-0099/0025.Reverse Nodes in k-Group/README_EN.md deleted file mode 100644 index f2ee5e78..00000000 --- a/leetcode/solution/0000-0099/0025.Reverse Nodes in k-Group/README_EN.md +++ /dev/null @@ -1,52 +0,0 @@ -# [25. Reverse Nodes in k-Group](https://leetcode.com/problems/reverse-nodes-in-k-group) - -[中文文档](/solution/0000-0099/0025.Reverse%20Nodes%20in%20k-Group/README.md) - -## Description - -1->2->3->4
, you should return the list as2->1->4->3
. - -
Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.
- -k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.
- -Example:
- -Given this linked list: 1->2->3->4->5
For k = 2, you should return: 2->1->4->3->5
For k = 3, you should return: 3->2->1->4->5
Note:
- -Given a sorted array nums, remove the duplicates in-place such that each element appear only once and return the new length.
- -Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
- -Example 1:
- -- -Given nums = [1,1,2], - - - -Your function should return length =- -2
, with the first two elements ofnums
being1
and2
respectively. - - - -It doesn't matter what you leave beyond the returned length.
Example 2:
- -- -Given nums = [0,0,1,1,1,2,2,3,3,4], - - - -Your function should return length =- -5
, with the first five elements ofnums
being modified to0
,1
,2
,3
, and4
respectively. - - - -It doesn't matter what values are set beyond the returned length. - -
Clarification:
- -Confused why the returned value is an integer but your answer is an array?
- -Note that the input array is passed in by reference, which means modification to the input array will be known to the caller as well.
- -Internally you can think of this:
- -- -// nums is passed in by reference. (i.e., without making a copy) - -int len = removeDuplicates(nums); - - - -// any modification to nums in your function would be known by the caller. - -// using the length returned by your function, it prints the first len elements. - -for (int i = 0; i < len; i++) { - - print(nums[i]); - -}- -## Solutions - - - -### **Python3** - -```python -class Solution: - def removeDuplicates(self, nums: List[int]) -> int: - cnt, n = 0, len(nums) - for i in range(1, n): - if nums[i] == nums[i - 1]: - cnt += 1 - else: - nums[i - cnt] = nums[i] - return n - cnt -``` - -### **Java** - -```java -class Solution { - public int removeDuplicates(int[] nums) { - int cnt = 0, n = nums.length; - for (int i = 1; i < n; ++i) { - if (nums[i] == nums[i - 1]) ++cnt; - else nums[i - cnt] = nums[i]; - } - return n - cnt; - } -} -``` - -### **JavaScript** - -```js -/** - * @param {number[]} nums - * @return {number} - */ -var removeDuplicates = function (nums) { - let cnt = 0; - const n = nums.length; - for (let i = 1; i < n; ++i) { - if (nums[i] == nums[i - 1]) ++cnt; - else nums[i - cnt] = nums[i]; - } - return n - cnt; -}; -``` - -### **...** - -``` - -``` - - diff --git a/leetcode/solution/0000-0099/0026.Remove Duplicates from Sorted Array/Solution.cs b/leetcode/solution/0000-0099/0026.Remove Duplicates from Sorted Array/Solution.cs deleted file mode 100644 index fd609b9c..00000000 --- a/leetcode/solution/0000-0099/0026.Remove Duplicates from Sorted Array/Solution.cs +++ /dev/null @@ -1,18 +0,0 @@ -import java.util.*; - -public class Solution { - public int RemoveDuplicates(int[] nums) { - if (nums.Length < 2) return nums.Length; - var i = 0; - var j = 1; - while (j < nums.Length) - { - if (nums[i] != nums[j]) - { - nums[++i] = nums[j]; - } - ++j; - } - return i + 1; - } -} \ No newline at end of file diff --git a/leetcode/solution/0000-0099/0026.Remove Duplicates from Sorted Array/Solution.go b/leetcode/solution/0000-0099/0026.Remove Duplicates from Sorted Array/Solution.go deleted file mode 100644 index eefc3be3..00000000 --- a/leetcode/solution/0000-0099/0026.Remove Duplicates from Sorted Array/Solution.go +++ /dev/null @@ -1,21 +0,0 @@ -/** - * @lc app=leetcode.cn id=26 lang=golang - * Accepted - * 161/161 cases passed (144 ms) - * Your runtime beats 36.91 % of golang submissions - * Your memory usage beats 40.4 % of golang submissions (8.2 MB) - */ - -func removeDuplicates(nums []int) int { - if nums == nil || len(nums) == 0 { - return 0 - } - j := 0 - for i := 1; i < len(nums); i++ { - if nums[j] != nums[i] { - j++ - nums[j] = nums[i] - } - } - return j + 1 -} diff --git a/leetcode/solution/0000-0099/0026.Remove Duplicates from Sorted Array/Solution.js b/leetcode/solution/0000-0099/0026.Remove Duplicates from Sorted Array/Solution.js deleted file mode 100644 index 105efa46..00000000 --- a/leetcode/solution/0000-0099/0026.Remove Duplicates from Sorted Array/Solution.js +++ /dev/null @@ -1,13 +0,0 @@ -/** - * @param {number[]} nums - * @return {number} - */ -var removeDuplicates = function (nums) { - let cnt = 0; - const n = nums.length; - for (let i = 1; i < n; ++i) { - if (nums[i] == nums[i - 1]) ++cnt; - else nums[i - cnt] = nums[i]; - } - return n - cnt; -}; diff --git a/leetcode/solution/0000-0099/0026.Remove Duplicates from Sorted Array/Solution.py b/leetcode/solution/0000-0099/0026.Remove Duplicates from Sorted Array/Solution.py deleted file mode 100644 index fb3d0986..00000000 --- a/leetcode/solution/0000-0099/0026.Remove Duplicates from Sorted Array/Solution.py +++ /dev/null @@ -1,9 +0,0 @@ -class Solution: - def removeDuplicates(self, nums: List[int]) -> int: - cnt, n = 0, len(nums) - for i in range(1, n): - if nums[i] == nums[i - 1]: - cnt += 1 - else: - nums[i - cnt] = nums[i] - return n - cnt diff --git a/leetcode/solution/0000-0099/0027.Remove Element/README_EN.md b/leetcode/solution/0000-0099/0027.Remove Element/README_EN.md deleted file mode 100644 index f6d9c15f..00000000 --- a/leetcode/solution/0000-0099/0027.Remove Element/README_EN.md +++ /dev/null @@ -1,134 +0,0 @@ -# [27. Remove Element](https://leetcode.com/problems/remove-element) - -[中文文档](/solution/0000-0099/0027.Remove%20Element/README.md) - -## Description - -
Given an array nums and a value val, remove all instances of that value in-place and return the new length.
- -Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
- -The order of elements can be changed. It doesn't matter what you leave beyond the new length.
- -Example 1:
- -- -Given nums = [3,2,2,3], val = 3, - - - -Your function should return length = 2, with the first two elements of nums being 2. - - - -It doesn't matter what you leave beyond the returned length. - -- -
Example 2:
- -- -Given nums = [0,1,2,2,3,0,4,2], val = 2, - - - -Your function should return length =- -5
, with the first five elements ofnums
containing0
,1
,3
,0
, and 4. - - - -Note that the order of those five elements can be arbitrary. - - - -It doesn't matter what values are set beyond the returned length.
Clarification:
- -Confused why the returned value is an integer but your answer is an array?
- -Note that the input array is passed in by reference, which means modification to the input array will be known to the caller as well.
- -Internally you can think of this:
- -- -// nums is passed in by reference. (i.e., without making a copy) - -int len = removeElement(nums, val); - - - -// any modification to nums in your function would be known by the caller. - -// using the length returned by your function, it prints the first len elements. - -for (int i = 0; i < len; i++) { - - print(nums[i]); - -}- -## Solutions - - - -### **Python3** - -```python -class Solution: - def removeElement(self, nums: List[int], val: int) -> int: - cnt, n = 0, len(nums) - for i in range(n): - if nums[i] == val: - cnt += 1 - else: - nums[i - cnt] = nums[i] - return n - cnt -``` - -### **Java** - -```java -class Solution { - public int removeElement(int[] nums, int val) { - int cnt = 0, n = nums.length; - for (int i = 0; i < n; ++i) { - if (nums[i] == val) { - ++cnt; - } else { - nums[i - cnt] = nums[i]; - } - } - return n - cnt; - } -} -``` - -### **C++** - -```cpp -class Solution { -public: - int removeElement(vector
Implement strStr().
- -Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
- -Example 1:
- -- -Input: haystack = "hello", needle = "ll" - -Output: 2 - -- -
Example 2:
- -- -Input: haystack = "aaaaa", needle = "bba" - -Output: -1 - -- -
Clarification:
- -What should we return when needle
is an empty string? This is a great question to ask during an interview.
For the purpose of this problem, we will return 0 when needle
is an empty string. This is consistent to C's strstr() and Java's indexOf().
Given two integers dividend
and divisor
, divide two integers without using multiplication, division and mod operator.
Return the quotient after dividing dividend
by divisor
.
The integer division should truncate toward zero, which means losing its fractional part. For example, truncate(8.345) = 8
and truncate(-2.7335) = -2
.
Example 1:
- --Input: dividend = 10, divisor = 3 -Output: 3 -Explanation: 10/3 = truncate(3.33333..) = 3. -- -
Example 2:
- --Input: dividend = 7, divisor = -3 -Output: -2 -Explanation: 7/-3 = truncate(-2.33333..) = -2. -- -
Note:
- -You are given a string, s, and a list of words, words, that are all of the same length. Find all starting indices of substring(s) in s that is a concatenation of each word in words exactly once and without any intervening characters.
- -- -
Example 1:
- -
-Input:
- s = "barfoothefoobarman",
- words = ["foo","bar"]
-Output: [0,9]
-Explanation: Substrings starting at index 0 and 9 are "barfoo" and "foobar" respectively.
-The output order does not matter, returning [9,0] is fine too.
-
-
-Example 2:
- -
-Input:
- s = "wordgoodgoodgoodbestword",
- words = ["word","good","best","word"]
-Output: []
-
-
-## Solutions
-
-
-
-### **Python3**
-
-```python
-
-```
-
-### **Java**
-
-```java
-
-```
-
-### **...**
-
-```
-
-```
-
-
diff --git a/leetcode/solution/0000-0099/0030.Substring with Concatenation of All Words/Solution.cs b/leetcode/solution/0000-0099/0030.Substring with Concatenation of All Words/Solution.cs
deleted file mode 100644
index 2bffa0ba..00000000
--- a/leetcode/solution/0000-0099/0030.Substring with Concatenation of All Words/Solution.cs
+++ /dev/null
@@ -1,59 +0,0 @@
-using System.Collections.Generic;
-
-import java.util.*;
-
-public class Solution {
- public IListImplement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.
- -If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).
- -The replacement must be in-place and use only constant extra memory.
- -Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column.
- -1,2,3
→ 1,3,2
-
-3,2,1
→ 1,2,3
-
-1,1,5
→ 1,5,1
Given a string containing just the characters '('
and ')'
, find the length of the longest valid (well-formed) parentheses substring.
Example 1:
- -
-
-Input: "(()"
-
-Output: 2
-
-Explanation: The longest valid parentheses substring is "()"
-
-
-
-Example 2:
- -- -Input: "- -## Solutions - - - -### **Python3** - -```python - -``` - -### **Java** - -```java - -``` - -### **...** - -``` - -``` - - diff --git a/leetcode/solution/0000-0099/0032.Longest Valid Parentheses/Solution.cs b/leetcode/solution/0000-0099/0032.Longest Valid Parentheses/Solution.cs deleted file mode 100644 index c459256a..00000000 --- a/leetcode/solution/0000-0099/0032.Longest Valid Parentheses/Solution.cs +++ /dev/null @@ -1,42 +0,0 @@ -using System.Collections.Generic; - -import java.util.*; - -public class Solution { - public int LongestValidParentheses(string s) { - var result = 0; - var baseCount = 0; - var stack = new Stack)()())
" - -Output: 4 - -Explanation: The longest valid parentheses substring is"()()"
- -
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).
- -Example 1:
- -
-
-Input: nums = [4,5,6,7,0,1,2]
, target = 0
-
-Output: 4
-
-
-
-Example 2:
- -
-
-Input: nums = [4,5,6,7,0,1,2]
, target = 3
-
-Output: -1
-
-## Solutions
-
-
-
-### **Python3**
-
-```python
-
-```
-
-### **Java**
-
-```java
-
-```
-
-### **...**
-
-```
-
-```
-
-
diff --git a/leetcode/solution/0000-0099/0033.Search in Rotated Sorted Array/Solution.cpp b/leetcode/solution/0000-0099/0033.Search in Rotated Sorted Array/Solution.cpp
deleted file mode 100644
index e4fce73a..00000000
--- a/leetcode/solution/0000-0099/0033.Search in Rotated Sorted Array/Solution.cpp
+++ /dev/null
@@ -1,36 +0,0 @@
-class Solution {
-public:
- int search(vectornums
sorted in ascending order, find the starting and ending position of a given target
value.
-
-Your algorithm's runtime complexity must be in the order of O(log n).
- -If the target is not found in the array, return [-1, -1]
.
Example 1:
- -
-
-Input: nums = [5,7,7,8,8,10]
, target = 8
-
-Output: [3,4]
-
-Example 2:
- -
-
-Input: nums = [5,7,7,8,8,10]
, target = 6
-
-Output: [-1,-1]
-
-## Solutions
-
-
-
-### **Python3**
-
-```python
-
-```
-
-### **Java**
-
-```java
-
-```
-
-### **...**
-
-```
-
-```
-
-
diff --git a/leetcode/solution/0000-0099/0034.Find First and Last Position of Element in Sorted Array/Solution.cpp b/leetcode/solution/0000-0099/0034.Find First and Last Position of Element in Sorted Array/Solution.cpp
deleted file mode 100644
index 7db0428a..00000000
--- a/leetcode/solution/0000-0099/0034.Find First and Last Position of Element in Sorted Array/Solution.cpp
+++ /dev/null
@@ -1,46 +0,0 @@
-class Solution {
-public:
- bool binarySearch(vectorGiven a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.
- -You may assume no duplicates in the array.
- -Example 1:
- -- -Input: [1,3,5,6], 5 - -Output: 2 - -- -
Example 2:
- -- -Input: [1,3,5,6], 2 - -Output: 1 - -- -
Example 3:
- -- -Input: [1,3,5,6], 7 - -Output: 4 - -- -
Example 4:
- -- -Input: [1,3,5,6], 0 - -Output: 0 - -- -## Solutions - - - -### **Python3** - -```python -class Solution: - def searchInsert(self, nums: List[int], target: int) -> int: - l, h = 0, len(nums) - 1 - while l <= h: - m = l + ((h - l) >> 1) - if nums[m] == target: - return m - if nums[m] < target: - l = m + 1 - else: - h = m - 1 - return l -``` - -### **Java** - -```java -class Solution { - public int searchInsert(int[] nums, int target) { - int l = 0, h = nums.length - 1; - while (l <= h) { - int m = l + ((h - l) >> 1); - if (nums[m] == target) return m; - if (nums[m] < target) l = m + 1; - else h = m - 1; - } - return l; - } -} -``` - -### **Go** - -```go -func searchInsert(nums []int, target int) int { - l, h := 0, len(nums) - 1 - for l <= h { - m := l + ((h - l) >> 1) - if nums[m] == target { - return m - } - if nums[m] < target { - l = m + 1 - } else { - h = m - 1 - } - } - return l -} -``` - -### **C++** - -```cpp -class Solution { -public: - int searchInsert(vector
Determine if a 9x9 Sudoku board is valid. Only the filled cells need to be validated according to the following rules:
- -1-9
without repetition.1-9
without repetition.3x3
sub-boxes of the grid must contain the digits 1-9
without repetition.
-
-A partially filled sudoku which is valid.
The Sudoku board could be partially filled, where empty cells are filled with the character '.'
.
Example 1:
- -- -Input: - -[ - - ["5","3",".",".","7",".",".",".","."], - - ["6",".",".","1","9","5",".",".","."], - - [".","9","8",".",".",".",".","6","."], - - ["8",".",".",".","6",".",".",".","3"], - - ["4",".",".","8",".","3",".",".","1"], - - ["7",".",".",".","2",".",".",".","6"], - - [".","6",".",".",".",".","2","8","."], - - [".",".",".","4","1","9",".",".","5"], - - [".",".",".",".","8",".",".","7","9"] - -] - -Output: true - -- -
Example 2:
- -- -Input: - -[ - - ["8","3",".",".","7",".",".",".","."], - - ["6",".",".","1","9","5",".",".","."], - - [".","9","8",".",".",".",".","6","."], - - ["8",".",".",".","6",".",".",".","3"], - - ["4",".",".","8",".","3",".",".","1"], - - ["7",".",".",".","2",".",".",".","6"], - - [".","6",".",".",".",".","2","8","."], - - [".",".",".","4","1","9",".",".","5"], - - [".",".",".",".","8",".",".","7","9"] - -] - -Output: false - -Explanation: Same as Example 1, except with the 5 in the top left corner being - - modified to 8. Since there are two 8's in the top left 3x3 sub-box, it is invalid. - -- -
Note:
- -1-9
and the character '.'
.9x9
.Write a program to solve a Sudoku puzzle by filling the empty cells.
- -A sudoku solution must satisfy all of the following rules:
- -1-9
must occur exactly once in each row.1-9
must occur exactly once in each column.1-9
must occur exactly once in each of the 9 3x3
sub-boxes of the grid.Empty cells are indicated by the character '.'
.
-
-A sudoku puzzle...
-
-...and its solution numbers marked in red.
Note:
- -1-9
and the character '.'
.9x9
.The count-and-say sequence is the sequence of integers with the first five terms as following:
- --1. 1 -2. 11 -3. 21 -4. 1211 -5. 111221 -- -
1
is read off as "one 1"
or 11
.
-11
is read off as "two 1s"
or 21
.
-21
is read off as "one 2
, then one 1"
or 1211
.
Given an integer n where 1 ≤ n ≤ 30, generate the nth term of the count-and-say sequence. You can do so recursively, in other words from the previous member read off the digits, counting the number of digits in groups of the same digit.
- -Note: Each term of the sequence of integers will be represented as a string.
- -- -
Example 1:
- --Input: 1 -Output: "1" -Explanation: This is the base case. -- -
Example 2:
- --Input: 4 -Output: "1211" -Explanation: For n = 3 the term was "21" in which we have two groups "2" and "1", "2" can be read as "12" which means frequency = 1 and value = 2, the same way "1" is read as "11", so the answer is the concatenation of "12" and "11" which is "1211". -- -## Solutions - - - -### **Python3** - -```python - -``` - -### **Java** - -```java - -``` - -### **...** - -``` - -``` - - diff --git a/leetcode/solution/0000-0099/0038.Count and Say/Solution.cs b/leetcode/solution/0000-0099/0038.Count and Say/Solution.cs deleted file mode 100644 index 63fb351e..00000000 --- a/leetcode/solution/0000-0099/0038.Count and Say/Solution.cs +++ /dev/null @@ -1,39 +0,0 @@ -using System.Text; -import java.util.*; - -public class Solution { - public string CountAndSay(int n) { - var s = "1"; - while (n > 1) - { - var sb = new StringBuilder(); - var lastChar = '1'; - var count = 0; - foreach (var ch in s) - { - if (count > 0 && lastChar == ch) - { - ++count; - } - else - { - if (count > 0) - { - sb.Append(count); - sb.Append(lastChar); - } - lastChar = ch; - count = 1; - } - } - if (count > 0) - { - sb.Append(count); - sb.Append(lastChar); - } - s = sb.ToString(); - --n; - } - return s; - } -} \ No newline at end of file diff --git a/leetcode/solution/0000-0099/0038.Count and Say/Solution.go b/leetcode/solution/0000-0099/0038.Count and Say/Solution.go deleted file mode 100644 index 63e7d0dc..00000000 --- a/leetcode/solution/0000-0099/0038.Count and Say/Solution.go +++ /dev/null @@ -1,22 +0,0 @@ -func countAndSay(n int) string { - buf := bytes.NewBufferString("1") - for i := 2; i <= n; i++ { - s := buf.String() - c, l := s[0:1], len(s) - buf.Reset() - count := 0 - for j := 0; j < l; j++ { - if c == s[j:j+1] { - count++ - } else { - buf.WriteByte(byte(48 + count)) - buf.WriteString(c) - count = 1 - c = s[j : j+1] - } - } - buf.WriteByte(byte(48 + count)) - buf.WriteString(c) - } - return buf.String() -} diff --git a/leetcode/solution/0000-0099/0038.Count and Say/Solution.js b/leetcode/solution/0000-0099/0038.Count and Say/Solution.js deleted file mode 100644 index 972b40d3..00000000 --- a/leetcode/solution/0000-0099/0038.Count and Say/Solution.js +++ /dev/null @@ -1,20 +0,0 @@ -const countAndSay = function (n) { - let s = "1"; - - for (let i = 2; i <= n; i++) { - let count = 1, - str = "", - len = s.length; - - for (let j = 0; j < len; j++) { - if (j < len - 1 && s[j] === s[j + 1]) { - count++; - } else { - str += `${count}${s[j]}`; - count = 1; - } - } - s = str; - } - return s; -}; diff --git a/leetcode/solution/0000-0099/0038.Count and Say/Solution.py b/leetcode/solution/0000-0099/0038.Count and Say/Solution.py deleted file mode 100644 index e646f64c..00000000 --- a/leetcode/solution/0000-0099/0038.Count and Say/Solution.py +++ /dev/null @@ -1,18 +0,0 @@ -class Solution(object): - def countAndSay(self, n): - s = '1' #初始化第一个数字 - for i in range(n-1): #n-1个数 - temp = '' #一个空数列 - num = s[0] #s的第一位数字 - count = 0 #当前数字的个数 - - for j in s: #遍历s中的每个字母 - if num == j: #如果这个字母和num一样 - count += 1 #计数+1 - else: - temp += str(count)+str(num) #存下“几”个“什么数” - num = j #num改成当前数字 - count = 1 #计数回到1 - temp += str(count)+str(num) #加的是最后一个 - s = temp - return s diff --git a/leetcode/solution/0000-0099/0039.Combination Sum/README_EN.md b/leetcode/solution/0000-0099/0039.Combination Sum/README_EN.md deleted file mode 100644 index 3e850c83..00000000 --- a/leetcode/solution/0000-0099/0039.Combination Sum/README_EN.md +++ /dev/null @@ -1,78 +0,0 @@ -# [39. Combination Sum](https://leetcode.com/problems/combination-sum) - -[中文文档](/solution/0000-0099/0039.Combination%20Sum/README.md) - -## Description - -
Given a set of candidate numbers (candidates
) (without duplicates) and a target number (target
), find all unique combinations in candidates
where the candidate numbers sums to target
.
The same repeated number may be chosen from candidates
unlimited number of times.
Note:
- -target
) will be positive integers.Example 1:
- -- -Input: candidates =- -[2,3,6,7],
target =7
, - -A solution set is: - -[ - - [7], - - [2,2,3] - -] - -
Example 2:
- -
-
-Input: candidates = [2,3,5],
target = 8,
-
-A solution set is:
-
-[
-
- [2,2,2,2],
-
- [2,3,3],
-
- [3,5]
-
-]
-
-
-
-## Solutions
-
-
-
-### **Python3**
-
-```python
-
-```
-
-### **Java**
-
-```java
-
-```
-
-### **...**
-
-```
-
-```
-
-
diff --git a/leetcode/solution/0000-0099/0039.Combination Sum/Solution.cpp b/leetcode/solution/0000-0099/0039.Combination Sum/Solution.cpp
deleted file mode 100644
index dfd77c92..00000000
--- a/leetcode/solution/0000-0099/0039.Combination Sum/Solution.cpp
+++ /dev/null
@@ -1,23 +0,0 @@
-class Solution {
-public:
- vectorGiven a collection of candidate numbers (candidates
) and a target number (target
), find all unique combinations in candidates
where the candidate numbers sums to target
.
Each number in candidates
may only be used once in the combination.
Note:
- -target
) will be positive integers.Example 1:
- -- -Input: candidates =- -[10,1,2,7,6,1,5]
, target =8
, - -A solution set is: - -[ - - [1, 7], - - [1, 2, 5], - - [2, 6], - - [1, 1, 6] - -] - -
Example 2:
- -- -Input: candidates = [2,5,2,1,2], target = 5, - -A solution set is: - -[ - - [1,2,2], - - [5] - -] - -- -## Solutions - - - -### **Python3** - -```python - -``` - -### **Java** - -```java - -``` - -### **...** - -``` - -``` - - diff --git a/leetcode/solution/0000-0099/0040.Combination Sum II/Solution.cpp b/leetcode/solution/0000-0099/0040.Combination Sum II/Solution.cpp deleted file mode 100644 index f935d698..00000000 --- a/leetcode/solution/0000-0099/0040.Combination Sum II/Solution.cpp +++ /dev/null @@ -1,27 +0,0 @@ -class Solution { -public: - vector
Given an unsorted integer array, find the smallest missing positive integer.
- -Example 1:
- -- -Input: [1,2,0] - -Output: 3 - -- -
Example 2:
- -- -Input: [3,4,-1,1] - -Output: 2 - -- -
Example 3:
- -- -Input: [7,8,9,11,12] - -Output: 1 - -- -
Note:
- -Your algorithm should run in O(n) time and uses constant extra space.
- -## Solutions - - - -### **Python3** - -```python - -``` - -### **Java** - -```java - -``` - -### **...** - -``` - -``` - - diff --git a/leetcode/solution/0000-0099/0041.First Missing Positive/Solution.c b/leetcode/solution/0000-0099/0041.First Missing Positive/Solution.c deleted file mode 100644 index 6e859a40..00000000 --- a/leetcode/solution/0000-0099/0041.First Missing Positive/Solution.c +++ /dev/null @@ -1,22 +0,0 @@ -int firstMissingPositive(int* nums, int numsSize) { - - int Max = nums[0], i, *Count; - - for(i = 1; iGiven n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.
- - - -The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped. Thanks Marcos for contributing this image! - -Example:
- -- -Input: [0,1,0,2,1,0,1,3,2,1,2,1] - -Output: 6- -## Solutions - - - -### **Python3** - -```python - -``` - -### **Java** - -```java - -``` - -### **...** - -``` - -``` - - diff --git a/leetcode/solution/0000-0099/0042.Trapping Rain Water/Solution.cpp b/leetcode/solution/0000-0099/0042.Trapping Rain Water/Solution.cpp deleted file mode 100644 index c2c7dd08..00000000 --- a/leetcode/solution/0000-0099/0042.Trapping Rain Water/Solution.cpp +++ /dev/null @@ -1,38 +0,0 @@ -class Solution { -public: - int trap(vector
Given two non-negative integers num1
and num2
represented as strings, return the product of num1
and num2
, also represented as a string.
Example 1:
- -- -Input: num1 = "2", num2 = "3" - -Output: "6"- -
Example 2:
- -- -Input: num1 = "123", num2 = "456" - -Output: "56088" - -- -
Note:
- -num1
and num2
is < 110.num1
and num2
contain only digits 0-9
.num1
and num2
do not contain any leading zero, except the number 0 itself.Given an input string (s
) and a pattern (p
), implement wildcard pattern matching with support for '?'
and '*'
.
- -'?' Matches any single character. - -'*' Matches any sequence of characters (including the empty sequence). - -- -
The matching should cover the entire input string (not partial).
- -Note:
- -s
could be empty and contains only lowercase letters a-z
.p
could be empty and contains only lowercase letters a-z
, and characters like ?
or *
.Example 1:
- -- -Input: - -s = "aa" - -p = "a" - -Output: false - -Explanation: "a" does not match the entire string "aa". - -- -
Example 2:
- -- -Input: - -s = "aa" - -p = "*" - -Output: true - -Explanation: '*' matches any sequence. - -- -
Example 3:
- -- -Input: - -s = "cb" - -p = "?a" - -Output: false - -Explanation: '?' matches 'c', but the second letter is 'a', which does not match 'b'. - -- -
Example 4:
- -- -Input: - -s = "adceb" - -p = "*a*b" - -Output: true - -Explanation: The first '*' matches the empty sequence, while the second '*' matches the substring "dce". - -- -
Example 5:
- -- -Input: - -s = "acdcb" - -p = "a*c?b" - -Output: false - -- -## Solutions - - - -### **Python3** - -```python - -``` - -### **Java** - -```java - -``` - -### **...** - -``` - -``` - - diff --git a/leetcode/solution/0000-0099/0044.Wildcard Matching/Solution.cs b/leetcode/solution/0000-0099/0044.Wildcard Matching/Solution.cs deleted file mode 100644 index 1d6030ba..00000000 --- a/leetcode/solution/0000-0099/0044.Wildcard Matching/Solution.cs +++ /dev/null @@ -1,45 +0,0 @@ -using System.Linq; - -import java.util.*; - -public class Solution { - public bool IsMatch(string s, string p) { - if (p.Count(ch => ch != '*') > s.Length) - { - return false; - } - - bool[,] f = new bool[s.Length + 1, p.Length + 1]; - bool[] d = new bool[s.Length + 1]; // d[i] means f[0, j] || f[1, j] || ... || f[i, j] - for (var j = 0; j <= p.Length; ++j) - { - d[0] = j == 0 ? true : d[0] && p[j - 1] == '*'; - for (var i = 0; i <= s.Length; ++i) - { - if (j == 0) - { - f[i, j] = i == 0; - continue; - } - - if (p[j - 1] == '*') - { - if (i > 0) - { - d[i] = f[i, j - 1] || d[i - 1]; - } - f[i, j] = d[i]; - } - else if (p[j - 1] == '?') - { - f[i, j] = i > 0 && f[i - 1, j - 1]; - } - else - { - f[i, j] = i > 0 && f[i - 1, j - 1] && s[i - 1] == p[j - 1]; - } - } - } - return f[s.Length, p.Length]; - } -} \ No newline at end of file diff --git a/leetcode/solution/0000-0099/0045.Jump Game II/README_EN.md b/leetcode/solution/0000-0099/0045.Jump Game II/README_EN.md deleted file mode 100644 index 66a24073..00000000 --- a/leetcode/solution/0000-0099/0045.Jump Game II/README_EN.md +++ /dev/null @@ -1,51 +0,0 @@ -# [45. Jump Game II](https://leetcode.com/problems/jump-game-ii) - -[中文文档](/solution/0000-0099/0045.Jump%20Game%20II/README.md) - -## Description - -
Given an array of non-negative integers, you are initially positioned at the first index of the array.
- -Each element in the array represents your maximum jump length at that position.
- -Your goal is to reach the last index in the minimum number of jumps.
- -Example:
- -- -Input: [2,3,1,1,4] - -Output: 2 - -Explanation: The minimum number of jumps to reach the last index is 2. - - Jump 1 step from index 0 to 1, then 3 steps to the last index.- -
Note:
- -You can assume that you can always reach the last index.
- -## Solutions - - - -### **Python3** - -```python - -``` - -### **Java** - -```java - -``` - -### **...** - -``` - -``` - - diff --git a/leetcode/solution/0000-0099/0045.Jump Game II/Solution.cs b/leetcode/solution/0000-0099/0045.Jump Game II/Solution.cs deleted file mode 100644 index 9b772b9a..00000000 --- a/leetcode/solution/0000-0099/0045.Jump Game II/Solution.cs +++ /dev/null @@ -1,31 +0,0 @@ -using System; - -import java.util.*; - -public class Solution { - public int Jump(int[] nums) { - var steps = 0; - var maxJump = 0; - var i = 0; - while (maxJump + 1 < nums.Length) - { - var newMaxJump = maxJump; - for (var j = i; j < nums.Length && j <= maxJump; ++j) - { - newMaxJump = Math.Max(newMaxJump, j + nums[j]); - } - i = maxJump + 1; - if (newMaxJump > maxJump) - { - maxJump = newMaxJump; - ++steps; - } - else - { - break; - } - } - if (maxJump + 1 >= nums.Length) return steps; - return -1; - } -} \ No newline at end of file diff --git a/leetcode/solution/0000-0099/0046.Permutations/README_EN.md b/leetcode/solution/0000-0099/0046.Permutations/README_EN.md deleted file mode 100644 index c39f1319..00000000 --- a/leetcode/solution/0000-0099/0046.Permutations/README_EN.md +++ /dev/null @@ -1,57 +0,0 @@ -# [46. Permutations](https://leetcode.com/problems/permutations) - -[中文文档](/solution/0000-0099/0046.Permutations/README.md) - -## Description - -Given a collection of distinct integers, return all possible permutations.
- -Example:
- -- -Input: [1,2,3] - -Output: - -[ - - [1,2,3], - - [1,3,2], - - [2,1,3], - - [2,3,1], - - [3,1,2], - - [3,2,1] - -] - -- -## Solutions - - - -### **Python3** - -```python - -``` - -### **Java** - -```java - -``` - -### **...** - -``` - -``` - - diff --git a/leetcode/solution/0000-0099/0046.Permutations/Solution.cpp b/leetcode/solution/0000-0099/0046.Permutations/Solution.cpp deleted file mode 100644 index 53c6d493..00000000 --- a/leetcode/solution/0000-0099/0046.Permutations/Solution.cpp +++ /dev/null @@ -1,35 +0,0 @@ -class Solution { -public: - vector
Given a collection of numbers that might contain duplicates, return all possible unique permutations.
- -Example:
- -- -Input: [1,1,2] - -Output: - -[ - - [1,1,2], - - [1,2,1], - - [2,1,1] - -] - -- -## Solutions - - - -### **Python3** - -```python - -``` - -### **Java** - -```java - -``` - -### **...** - -``` - -``` - - diff --git a/leetcode/solution/0000-0099/0047.Permutations II/Solution.cpp b/leetcode/solution/0000-0099/0047.Permutations II/Solution.cpp deleted file mode 100644 index ebbe2211..00000000 --- a/leetcode/solution/0000-0099/0047.Permutations II/Solution.cpp +++ /dev/null @@ -1,41 +0,0 @@ -class Solution { -public: - vector
Rotate the image by 90 degrees (clockwise).
- -Note:
- -You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation.
- -Example 1:
- -- -Given input matrix = - -[ - - [1,2,3], - - [4,5,6], - - [7,8,9] - -], - - - -rotate the input matrix in-place such that it becomes: - -[ - - [7,4,1], - - [8,5,2], - - [9,6,3] - -] - -- -
Example 2:
- -- -Given input matrix = - -[ - - [ 5, 1, 9,11], - - [ 2, 4, 8,10], - - [13, 3, 6, 7], - - [15,14,12,16] - -], - - - -rotate the input matrix in-place such that it becomes: - -[ - - [15,13, 2, 5], - - [14, 3, 4, 1], - - [12, 6, 8, 9], - - [16, 7,10,11] - -] - -- -## Solutions - - - -### **Python3** - -```python -class Solution: - def rotate(self, matrix: List[List[int]]) -> None: - """ - Do not return anything, modify matrix in-place instead. - """ - s, n = 0, len(matrix) - while s < (n >> 1): - e = n - s - 1 - for i in range(s, e): - t = matrix[i][e] - matrix[i][e] = matrix[s][i] - matrix[s][i] = matrix[n - i - 1][s] - matrix[n - i - 1][s] = matrix[e][n - i - 1] - matrix[e][n - i - 1] = t - s += 1 -``` - -### **Java** - -```java -class Solution { - public void rotate(int[][] matrix) { - int s = 0, n = matrix.length; - while (s < (n >> 1)) { - int e = n - s - 1; - for (int i = s; i < e; ++i) { - int t = matrix[i][e]; - matrix[i][e] = matrix[s][i]; - matrix[s][i] = matrix[n - i - 1][s]; - matrix[n - i - 1][s] = matrix[e][n - i - 1]; - matrix[e][n - i - 1] = t; - } - ++s; - } - } -} -``` - -### **...** - -``` - -``` - - diff --git a/leetcode/solution/0000-0099/0048.Rotate Image/Solution.cpp b/leetcode/solution/0000-0099/0048.Rotate Image/Solution.cpp deleted file mode 100644 index 5c5418ad..00000000 --- a/leetcode/solution/0000-0099/0048.Rotate Image/Solution.cpp +++ /dev/null @@ -1,22 +0,0 @@ -class Solution { -public: - void rotate(vector
Given an array of strings, group anagrams together.
- -Example:
- -
-
-Input: ["eat", "tea", "tan", "ate", "nat", "bat"]
,
-
-Output:
-
-[
-
- ["ate","eat","tea"],
-
- ["nat","tan"],
-
- ["bat"]
-
-]
-
-Note:
- -Implement pow(x, n), which calculates x raised to the power n (xn).
- -Example 1:
- -- -Input: 2.00000, 10 - -Output: 1024.00000 - -- -
Example 2:
- -- -Input: 2.10000, 3 - -Output: 9.26100 - -- -
Example 3:
- -- -Input: 2.00000, -2 - -Output: 0.25000 - -Explanation: 2-2 = 1/22 = 1/4 = 0.25 - -- -
Note:
- -The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other.
- - - -Given an integer n, return all distinct solutions to the n-queens puzzle.
- -Each solution contains a distinct board configuration of the n-queens' placement, where 'Q'
and '.'
both indicate a queen and an empty space respectively.
Example:
- -- -Input: 4 - -Output: [ - - [".Q..", // Solution 1 - - "...Q", - - "Q...", - - "..Q."], - - - - ["..Q.", // Solution 2 - - "Q...", - - "...Q", - - ".Q.."] - -] - -Explanation: There exist two distinct solutions to the 4-queens puzzle as shown above. - -- -## Solutions - - - -### **Python3** - -```python - -``` - -### **Java** - -```java - -``` - -### **...** - -``` - -``` - - diff --git a/leetcode/solution/0000-0099/0051.N-Queens/Solution.cs b/leetcode/solution/0000-0099/0051.N-Queens/Solution.cs deleted file mode 100644 index a3dd5fb3..00000000 --- a/leetcode/solution/0000-0099/0051.N-Queens/Solution.cs +++ /dev/null @@ -1,51 +0,0 @@ -using System.Collections.Generic; -using System.Text; - -import java.util.*; - -public class Solution { - private IList
The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other.
- - - -Given an integer n, return the number of distinct solutions to the n-queens puzzle.
- -Example:
- -- -Input: 4 - -Output: 2 - -Explanation: There are two distinct solutions to the 4-queens puzzle as shown below. - -[ - - [".Q..", // Solution 1 - - "...Q", - - "Q...", - - "..Q."], - - - - ["..Q.", // Solution 2 - - "Q...", - - "...Q", - - ".Q.."] - -] - -- -## Solutions - - - -### **Python3** - -```python - -``` - -### **Java** - -```java - -``` - -### **...** - -``` - -``` - - diff --git a/leetcode/solution/0000-0099/0053.Maximum Subarray/README_EN.md b/leetcode/solution/0000-0099/0053.Maximum Subarray/README_EN.md deleted file mode 100644 index 4a7b0465..00000000 --- a/leetcode/solution/0000-0099/0053.Maximum Subarray/README_EN.md +++ /dev/null @@ -1,63 +0,0 @@ -# [53. Maximum Subarray](https://leetcode.com/problems/maximum-subarray) - -[中文文档](/solution/0000-0099/0053.Maximum%20Subarray/README.md) - -## Description - -
Given an integer array nums
, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.
Example:
- -- -Input: [-2,1,-3,4,-1,2,1,-5,4], - -Output: 6 - -Explanation: [4,-1,2,1] has the largest sum = 6. - -- -
Follow up:
- -If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.
- -## Solutions - - - -### **Python3** - -```python -class Solution: - def maxSubArray(self, nums: List[int]) -> int: - n = len(nums) - res = f = nums[0] - for i in range(1, n): - f = nums[i] + max(f, 0) - res = max(res, f) - return res -``` - -### **Java** - -```java -class Solution { - public int maxSubArray(int[] nums) { - int f = nums[0], res = nums[0]; - for (int i = 1, n = nums.length; i < n; ++i) { - f = nums[i] + Math.max(f, 0); - res = Math.max(res, f); - } - return res; - } -} -``` - -### **...** - -``` - -``` - - diff --git a/leetcode/solution/0000-0099/0053.Maximum Subarray/Solution.cpp b/leetcode/solution/0000-0099/0053.Maximum Subarray/Solution.cpp deleted file mode 100644 index 588e58ac..00000000 --- a/leetcode/solution/0000-0099/0053.Maximum Subarray/Solution.cpp +++ /dev/null @@ -1,74 +0,0 @@ -/* - * @lc app=leetcode.cn id=53 lang=cpp - * - * [53] 最大子序和 - * - * https://leetcode-cn.com/problems/maximum-subarray/description/ - * - * algorithms - * Easy (46.59%) - * Likes: 2144 - * Dislikes: 0 - * Total Accepted: 270.6K - * Total Submissions: 524.4K - * Testcase Example: '[-2,1,-3,4,-1,2,1,-5,4]' - * - * 给定一个整数数组 nums ,找到一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。 - * - * 示例: - * - * 输入: [-2,1,-3,4,-1,2,1,-5,4], - * 输出: 6 - * 解释: 连续子数组 [4,-1,2,1] 的和最大,为 6。 - * - * - * 进阶: - * - * 如果你已经实现复杂度为 O(n) 的解法,尝试使用更为精妙的分治法求解。 - * - */ - -#includeGiven a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
- -Example 1:
- -- -Input: - -[ - - [ 1, 2, 3 ], - - [ 4, 5, 6 ], - - [ 7, 8, 9 ] - -] - -Output: [1,2,3,6,9,8,7,4,5] - -- -
Example 2:
- -- -Input: - -[ - - [1, 2, 3, 4], - - [5, 6, 7, 8], - - [9,10,11,12] - -] - -Output: [1,2,3,4,8,12,11,10,9,5,6,7] - -- -**Constraints:** - -- m == matrix.length -- n == matrix[i].length -- 1 <= m, n <= 10 -- -100 <= matrix[i][j] <= 100 - -## Solutions - - - -### **Python3** - -```python -class Solution: - def spiralOrder(self, matrix: List[List[int]]) -> List[int]: - def add(i1, j1, i2, j2): - if i1 == i2: - return [matrix[i1][j] for j in range(j1, j2 + 1)] - if j1 == j2: - return [matrix[i][j1] for i in range(i1, i2 + 1)] - return [matrix[i1][j] for j in range(j1, j2)] + [matrix[i][j2] for i in range(i1, i2)] + [matrix[i2][j] for j in range(j2, j1, -1)] + [matrix[i][j1] for i in range(i2, i1, -1)] - - m, n = len(matrix), len(matrix[0]) - i1, j1, i2, j2 = 0, 0, m - 1, n - 1 - res = [] - while i1 <= i2 and j1 <= j2: - res += add(i1, j1, i2, j2) - i1, j1, i2, j2 = i1 + 1, j1 + 1, i2 - 1, j2 - 1 - return res -``` - -### **Java** - -```java -class Solution { - private List
Given an array of non-negative integers, you are initially positioned at the first index of the array.
- -Each element in the array represents your maximum jump length at that position.
- -Determine if you are able to reach the last index.
- -Example 1:
- -- -Input: [2,3,1,1,4] - -Output: true - -Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index. - -- -
Example 2:
- -- -Input: [3,2,1,0,4] - -Output: false - -Explanation: You will always arrive at index 3 no matter what. Its maximum - - jump length is 0, which makes it impossible to reach the last index. - -- -## Solutions - - - -### **Python3** - -```python - -``` - -### **Java** - -```java - -``` - -### **...** - -``` - -``` - - diff --git a/leetcode/solution/0000-0099/0055.Jump Game/Solution.cs b/leetcode/solution/0000-0099/0055.Jump Game/Solution.cs deleted file mode 100644 index 1c5daa32..00000000 --- a/leetcode/solution/0000-0099/0055.Jump Game/Solution.cs +++ /dev/null @@ -1,21 +0,0 @@ -using System; - -import java.util.*; - -public class Solution { - public bool CanJump(int[] nums) { - var maxJump = 0; - for (var i = 0; i < nums.Length; ++i) - { - if (i <= maxJump) - { - maxJump = Math.Max(maxJump, i + nums[i]); - } - else - { - return false; - } - } - return true; - } -} \ No newline at end of file diff --git a/leetcode/solution/0000-0099/0056.Merge Intervals/README_EN.md b/leetcode/solution/0000-0099/0056.Merge Intervals/README_EN.md deleted file mode 100644 index a623ce44..00000000 --- a/leetcode/solution/0000-0099/0056.Merge Intervals/README_EN.md +++ /dev/null @@ -1,55 +0,0 @@ -# [56. Merge Intervals](https://leetcode.com/problems/merge-intervals) - -[中文文档](/solution/0000-0099/0056.Merge%20Intervals/README.md) - -## Description - -
Given a collection of intervals, merge all overlapping intervals.
- -Example 1:
- -- -Input: [[1,3],[2,6],[8,10],[15,18]] - -Output: [[1,6],[8,10],[15,18]] - -Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6]. - -- -
Example 2:
- -- -Input: [[1,4],[4,5]] - -Output: [[1,5]] - -Explanation: Intervals [1,4] and [4,5] are considered overlapping.- -
NOTE: input types have been changed on April 15, 2019. Please reset to default code definition to get new method signature.
- -## Solutions - - - -### **Python3** - -```python - -``` - -### **Java** - -```java - -``` - -### **...** - -``` - -``` - - diff --git a/leetcode/solution/0000-0099/0056.Merge Intervals/Solution.cpp b/leetcode/solution/0000-0099/0056.Merge Intervals/Solution.cpp deleted file mode 100644 index 4b9fb7a7..00000000 --- a/leetcode/solution/0000-0099/0056.Merge Intervals/Solution.cpp +++ /dev/null @@ -1,36 +0,0 @@ -/** - * Definition for an interval. - * struct Interval { - * int start; - * int end; - * Interval() : start(0), end(0) {} - * Interval(int s, int e) : start(s), end(e) {} - * }; - */ -bool cmp(Interval &val1,Interval &val2){ - return !(val1.start >= val2.start); -} - -class Solution { -public: - vectorGiven a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary).
- -You may assume that the intervals were initially sorted according to their start times.
- -Example 1:
- -- -Input: intervals = [[1,3],[6,9]], newInterval = [2,5] - -Output: [[1,5],[6,9]] - -- -
Example 2:
- -- -Input: intervals =- -[[1,2],[3,5],[6,7],[8,10],[12,16]]
, newInterval =[4,8]
- -Output: [[1,2],[3,10],[12,16]] - -Explanation: Because the new interval[4,8]
overlaps with[3,5],[6,7],[8,10]
.
NOTE: input types have been changed on April 15, 2019. Please reset to default code definition to get new method signature.
- -## Solutions - - - -### **Python3** - -```python - -``` - -### **Java** - -```java - -``` - -### **...** - -``` - -``` - - diff --git a/leetcode/solution/0000-0099/0057.Insert Interval/Solution.cpp b/leetcode/solution/0000-0099/0057.Insert Interval/Solution.cpp deleted file mode 100644 index f37571cf..00000000 --- a/leetcode/solution/0000-0099/0057.Insert Interval/Solution.cpp +++ /dev/null @@ -1,32 +0,0 @@ -bool cmp(Interval &val1,Interval &val2){ - return val1.start < val2.start; -} - -class Solution { -public: - vectorGiven a string s consists of upper/lower-case alphabets and empty space characters ' '
, return the length of last word (last word means the last appearing word if we loop from left to right) in the string.
If the last word does not exist, return 0.
- -Note: A word is defined as a maximal substring consisting of non-space characters only.
- -Example:
- --Input: "Hello World" -Output: 5 -- -
- -## Solutions - - - -### **Python3** - -```python -class Solution: - def lengthOfLastWord(self, s: str) -> int: - last_word_length = 0 - meet_word = False - for i in range(len(s) - 1, -1, -1): - ch = ord(s[i]) - if ch >= 65 and ch <= 122: - meet_word = True - last_word_length += 1 - elif meet_word: - break - return last_word_length -``` - -### **Java** - -```java -class Solution { - public int lengthOfLastWord(String s) { - int n = s.length(); - int lastWordLength = 0; - boolean meetWord = false; - for (int i = n - 1; i >= 0; --i) { - char ch = s.charAt(i); - if (ch >= 'A' && ch <= 'z') { - meetWord = true; - ++lastWordLength; - } else if (meetWord) { - break; - } - } - return lastWordLength; - } -} -``` - -### **...** - -``` - -``` - - diff --git a/leetcode/solution/0000-0099/0058.Length of Last Word/Solution.go b/leetcode/solution/0000-0099/0058.Length of Last Word/Solution.go deleted file mode 100644 index 9fad11e9..00000000 --- a/leetcode/solution/0000-0099/0058.Length of Last Word/Solution.go +++ /dev/null @@ -1,18 +0,0 @@ -func lengthOfLastWord(s string) int { - if len(s) == 0 { - return 0 - } - space := []byte(" ")[0] - for len(s) != 0 && s[len(s)-1] == space { - s = s[:len(s)-1] - } - ret := 0 - for i := len(s) - 1; i >= 0; i-- { - if s[i] != space { - ret++ - } else { - return ret - } - } - return ret -} diff --git a/leetcode/solution/0000-0099/0058.Length of Last Word/Solution.js b/leetcode/solution/0000-0099/0058.Length of Last Word/Solution.js deleted file mode 100644 index 348d2344..00000000 --- a/leetcode/solution/0000-0099/0058.Length of Last Word/Solution.js +++ /dev/null @@ -1,16 +0,0 @@ -var lengthOfLastWord = function (s) { - s = s.trim(); - return s.length - s.lastIndexOf(" ") - 1; -}; - -var lengthOfLastWord2 = function (s) { - let res = 0; - for (let i = 0; i < s.length; i++) { - if (s[i] !== " " && (i === 0 || s[i - 1] === " ")) { - res = 1; - } else if (s[i] !== " ") { - res++; - } - } - return res; -}; diff --git a/leetcode/solution/0000-0099/0058.Length of Last Word/Solution.py b/leetcode/solution/0000-0099/0058.Length of Last Word/Solution.py deleted file mode 100644 index 37b97e24..00000000 --- a/leetcode/solution/0000-0099/0058.Length of Last Word/Solution.py +++ /dev/null @@ -1,12 +0,0 @@ -class Solution: - def lengthOfLastWord(self, s: str) -> int: - last_word_length = 0 - meet_word = False - for i in range(len(s) - 1, -1, -1): - ch = ord(s[i]) - if ch >= 65 and ch <= 122: - meet_word = True - last_word_length += 1 - elif meet_word: - break - return last_word_length diff --git a/leetcode/solution/0000-0099/0059.Spiral Matrix II/README_EN.md b/leetcode/solution/0000-0099/0059.Spiral Matrix II/README_EN.md deleted file mode 100644 index f331f4bc..00000000 --- a/leetcode/solution/0000-0099/0059.Spiral Matrix II/README_EN.md +++ /dev/null @@ -1,133 +0,0 @@ -# [59. Spiral Matrix II](https://leetcode.com/problems/spiral-matrix-ii) - -[中文文档](/solution/0000-0099/0059.Spiral%20Matrix%20II/README.md) - -## Description - -
Given a positive integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
- -Example:
- -- -Input: 3 - -Output: - -[ - - [ 1, 2, 3 ], - - [ 8, 9, 4 ], - - [ 7, 6, 5 ] - -] - -- -## Solutions - - - -### **Python3** - -```python -class Solution: - def generateMatrix(self, n: int) -> List[List[int]]: - res = [[0] * n for _ in range(n)] - num = 1 - m1, m2 = 0, n - 1 - while m1 < m2: - for j in range(m1, m2): - res[m1][j] = num - num += 1 - for i in range(m1, m2): - res[i][m2] = num - num += 1 - for j in range(m2, m1, -1): - res[m2][j] = num - num += 1 - for i in range(m2, m1, -1): - res[i][m1] = num - num += 1 - m1 += 1 - m2 -= 1 - if m1 == m2: - res[m1][m1] = num - return res -``` - -### **Java** - -```java -class Solution { - public int[][] generateMatrix(int n) { - int[][] res = new int[n][n]; - int num = 1; - int m1 = 0, m2 = n - 1; - while (m1 < m2) { - for (int j = m1; j < m2; ++j) { - res[m1][j] = num++; - } - for (int i = m1; i < m2; ++i) { - res[i][m2] = num++; - } - for (int j = m2; j > m1; --j) { - res[m2][j] = num++; - } - for (int i = m2; i > m1; --i) { - res[i][m1] = num++; - } - ++m1; - --m2; - } - if (m1 == m2) { - res[m1][m1] = num; - } - - return res; - } -} -``` - -### **C++** - -```cpp -class Solution { -public: - vector