diff --git a/problems/0015.三数之和.md b/problems/0015.三数之和.md index 8992c5f4..e191eabc 100644 --- a/problems/0015.三数之和.md +++ b/problems/0015.三数之和.md @@ -545,5 +545,64 @@ int** threeSum(int* nums, int numsSize, int* returnSize, int** returnColumnSizes } ``` +C#: +```csharp +public class Solution +{ + public IList> ThreeSum(int[] nums) + { + var result = new List>(); + + Array.Sort(nums); + + for (int i = 0; i < nums.Length - 2; i++) + { + int n1 = nums[i]; + + if (n1 > 0) + break; + + if (i > 0 && n1 == nums[i - 1]) + continue; + + int left = i + 1; + int right = nums.Length - 1; + + while (left < right) + { + int n2 = nums[left]; + int n3 = nums[right]; + int sum = n1 + n2 + n3; + + if (sum > 0) + { + right--; + } + else if (sum < 0) + { + left++; + } + else + { + result.Add(new List { n1, n2, n3 }); + + while (left < right && nums[left] == n2) + { + left++; + } + + while (left < right && nums[right] == n3) + { + right--; + } + } + } + } + + return result; + } +} +``` + -----------------------
diff --git a/problems/0018.四数之和.md b/problems/0018.四数之和.md index dae8636b..bad258c1 100644 --- a/problems/0018.四数之和.md +++ b/problems/0018.四数之和.md @@ -445,5 +445,67 @@ func fourSum(_ nums: [Int], _ target: Int) -> [[Int]] { } ``` +C#: +```csharp +public class Solution +{ + public IList> FourSum(int[] nums, int target) + { + var result = new List>(); + + Array.Sort(nums); + + for (int i = 0; i < nums.Length - 3; i++) + { + int n1 = nums[i]; + if (i > 0 && n1 == nums[i - 1]) + continue; + + for (int j = i + 1; j < nums.Length - 2; j++) + { + int n2 = nums[j]; + if (j > i + 1 && n2 == nums[j - 1]) + continue; + + int left = j + 1; + int right = nums.Length - 1; + + while (left < right) + { + int n3 = nums[left]; + int n4 = nums[right]; + int sum = n1 + n2 + n3 + n4; + + if (sum > target) + { + right--; + } + else if (sum < target) + { + left++; + } + else + { + result.Add(new List { n1, n2, n3, n4 }); + + while (left < right && nums[left] == n3) + { + left++; + } + + while (left < right && nums[right] == n4) + { + right--; + } + } + } + } + } + + return result; + } +} +``` + -----------------------
diff --git a/problems/0028.实现strStr.md b/problems/0028.实现strStr.md index c23f5558..bbe5b80f 100644 --- a/problems/0028.实现strStr.md +++ b/problems/0028.实现strStr.md @@ -929,6 +929,83 @@ var strStr = function (haystack, needle) { }; ``` +TypeScript版本: + +> 前缀表统一减一 + +```typescript +function strStr(haystack: string, needle: string): number { + function getNext(str: string): number[] { + let next: number[] = []; + let j: number = -1; + next[0] = j; + for (let i = 1, length = str.length; i < length; i++) { + while (j >= 0 && str[i] !== str[j + 1]) { + j = next[j]; + } + if (str[i] === str[j + 1]) { + j++; + } + next[i] = j; + } + return next; + } + if (needle.length === 0) return 0; + let next: number[] = getNext(needle); + let j: number = -1; + for (let i = 0, length = haystack.length; i < length; i++) { + while (j >= 0 && haystack[i] !== needle[j + 1]) { + j = next[j]; + } + if (haystack[i] === needle[j + 1]) { + if (j === needle.length - 2) { + return i - j - 1; + } + j++; + } + } + return -1; +}; +``` + +> 前缀表不减一 + +```typescript +// 不减一版本 +function strStr(haystack: string, needle: string): number { + function getNext(str: string): number[] { + let next: number[] = []; + let j: number = 0; + next[0] = j; + for (let i = 1, length = str.length; i < length; i++) { + while (j > 0 && str[i] !== str[j]) { + j = next[j - 1]; + } + if (str[i] === str[j]) { + j++; + } + next[i] = j; + } + return next; + } + if (needle.length === 0) return 0; + let next: number[] = getNext(needle); + let j: number = 0; + for (let i = 0, length = haystack.length; i < length; i++) { + while (j > 0 && haystack[i] !== needle[j]) { + j = next[j - 1]; + } + if (haystack[i] === needle[j]) { + if (j === needle.length - 1) { + return i - j; + } + j++; + } + } + return -1; +} +``` + Swift 版本 > 前缀表统一减一 diff --git a/problems/0051.N皇后.md b/problems/0051.N皇后.md index 51415e88..7eb0d7a0 100644 --- a/problems/0051.N皇后.md +++ b/problems/0051.N皇后.md @@ -346,69 +346,56 @@ class Solution { ### Go ```Go -import "strings" -var res [][]string - -func isValid(board [][]string, row, col int) (res bool){ - n := len(board) - for i:=0; i < row; i++ { - if board[i][col] == "Q" { - return false - } - } - for i := 0; i < n; i++{ - if board[row][i] == "Q" { - return false - } - } - - for i ,j := row, col; i >= 0 && j >=0 ; i, j = i - 1, j- 1{ - if board[i][j] == "Q"{ - return false - } - } - for i, j := row, col; i >=0 && j < n; i,j = i-1, j+1 { - if board[i][j] == "Q" { - return false - } - } - return true -} - -func backtrack(board [][]string, row int) { - size := len(board) - if row == size{ - temp := make([]string, size) - for i := 0; i= 0 && j >= 0; i, j = i-1, j-1 { + if chessboard[i][j] == "Q" { + return false + } + } + for i, j := row-1, col+1; i >= 0 && j < n; i, j = i-1, j+1 { + if chessboard[i][j] == "Q" { + return false + } + } + return true } ``` ### Javascript diff --git a/problems/0054.螺旋矩阵.md b/problems/0054.螺旋矩阵.md index 3f85c607..ccf6f471 100644 --- a/problems/0054.螺旋矩阵.md +++ b/problems/0054.螺旋矩阵.md @@ -131,7 +131,46 @@ public: * [59.螺旋矩阵II](https://leetcode-cn.com/problems/spiral-matrix-ii/) * [剑指Offer 29.顺时针打印矩阵](https://leetcode-cn.com/problems/shun-shi-zhen-da-yin-ju-zhen-lcof/) +## 其他语言版本 +Python: +```python +class Solution: + def spiralOrder(self, matrix: List[List[int]]) -> List[int]: + m, n = len(matrix), len(matrix[0]) + left, right, up, down = 0, n - 1, 0, m - 1 # 定位四个方向的边界,闭区间 + res = [] + + while True: + for i in range(left, right + 1): # 上边,从左到右 + res.append(matrix[up][i]) + up += 1 # 上边界下移 + if len(res) >= m * n: # 判断是否已经遍历完 + break + + for i in range(up, down + 1): # 右边,从上到下 + res.append(matrix[i][right]) + right -= 1 # 右边界左移 + + if len(res) >= m * n: + break + + for i in range(right, left - 1, -1): # 下边,从右到左 + res.append(matrix[down][i]) + down -= 1 # 下边界上移 + + if len(res) >= m * n: + break + + for i in range(down, up - 1, -1): # 左边,从下到上 + res.append(matrix[i][left]) + left += 1 # 左边界右移 + + if len(res) >= m * n: + break + + return res +``` -----------------------
diff --git a/problems/0063.不同路径II.md b/problems/0063.不同路径II.md index 6f405d6a..105b6402 100644 --- a/problems/0063.不同路径II.md +++ b/problems/0063.不同路径II.md @@ -266,46 +266,33 @@ Go: ```go func uniquePathsWithObstacles(obstacleGrid [][]int) int { - m,n:= len(obstacleGrid),len(obstacleGrid[0]) + m, n := len(obstacleGrid), len(obstacleGrid[0]) // 定义一个dp数组 - dp := make([][]int,m) - for i,_ := range dp { - dp[i] = make([]int,n) + dp := make([][]int, m) + for i, _ := range dp { + dp[i] = make([]int, n) } - // 初始化 - for i:=0;i递归 +```swift +func isBalanced(_ root: TreeNode?) -> Bool { + // -1 已经不是平衡二叉树 + return getHeight(root) == -1 ? false : true +} +func getHeight(_ root: TreeNode?) -> Int { + guard let root = root else { + return 0 + } + let leftHeight = getHeight(root.left) + if leftHeight == -1 { + return -1 + } + let rightHeight = getHeight(root.right) + if rightHeight == -1 { + return -1 + } + if abs(leftHeight - rightHeight) > 1 { + return -1 + } else { + return 1 + max(leftHeight, rightHeight) + } +} +``` + -----------------------
diff --git a/problems/0151.翻转字符串里的单词.md b/problems/0151.翻转字符串里的单词.md index d58ace89..ead5fa12 100644 --- a/problems/0151.翻转字符串里的单词.md +++ b/problems/0151.翻转字符串里的单词.md @@ -553,6 +553,65 @@ function reverse(strArr, start, end) { } ``` +TypeScript: + +```typescript +function reverseWords(s: string): string { + /** Utils **/ + // 删除多余空格, 如' hello world ' => 'hello world' + function delExtraSpace(arr: string[]): void { + let left: number = 0, + right: number = 0, + length: number = arr.length; + while (right < length && arr[right] === ' ') { + right++; + } + while (right < length) { + if (arr[right] === ' ' && arr[right - 1] === ' ') { + right++; + continue; + } + arr[left++] = arr[right++]; + } + if (arr[left - 1] === ' ') { + arr.length = left - 1; + } else { + arr.length = left; + } + } + // 翻转字符串,如:'hello' => 'olleh' + function reverseWords(strArr: string[], start: number, end: number) { + let temp: string; + while (start < end) { + temp = strArr[start]; + strArr[start] = strArr[end]; + strArr[end] = temp; + start++; + end--; + } + } + + /** Main code **/ + let strArr: string[] = s.split(''); + delExtraSpace(strArr); + let length: number = strArr.length; + // 翻转整个字符串 + reverseWords(strArr, 0, length - 1); + let start: number = 0, + end: number = 0; + while (start < length) { + end = start; + while (strArr[end] !== ' ' && end < length) { + end++; + } + // 翻转单个单词 + reverseWords(strArr, start, end - 1); + start = end + 1; + } + return strArr.join(''); +}; +``` + Swift: ```swift diff --git a/problems/0257.二叉树的所有路径.md b/problems/0257.二叉树的所有路径.md index cb837d87..7b5fc2e9 100644 --- a/problems/0257.二叉树的所有路径.md +++ b/problems/0257.二叉树的所有路径.md @@ -581,7 +581,72 @@ var binaryTreePaths = function(root) { }; ``` +Swift: +> 递归/回溯 +```swift +func binaryTreePaths(_ root: TreeNode?) -> [String] { + var res = [String]() + guard let root = root else { + return res + } + var path = [Int]() + _binaryTreePaths(root, path: &path, res: &res) + return res +} +func _binaryTreePaths(_ root: TreeNode, path: inout [Int], res: inout [String]) { + path.append(root.val) + if root.left == nil && root.right == nil { + var str = "" + for i in 0 ..< path.count - 1 { + str.append("\(path[i])->") + } + str.append("\(path.last!)") + res.append(str) + return + } + if let left = root.left { + _binaryTreePaths(left, path: &path, res: &res) + path.removeLast() + } + if let right = root.right { + _binaryTreePaths(right, path: &path, res: &res) + path.removeLast() + } +} +``` + +> 迭代 +```swift +func binaryTreePaths(_ root: TreeNode?) -> [String] { + var res = [String]() + guard let root = root else { + return res + } + var stackNode = [TreeNode]() + stackNode.append(root) + + var stackStr = [String]() + stackStr.append("\(root.val)") + + while !stackNode.isEmpty { + let node = stackNode.popLast()! + let str = stackStr.popLast()! + if node.left == nil && node.right == nil { + res.append(str) + } + if let left = node.left { + stackNode.append(left) + stackStr.append("\(str)->\(left.val)") + } + if let right = node.right { + stackNode.append(right) + stackStr.append("\(str)->\(right.val)") + } + } + return res +} +``` -----------------------
diff --git a/problems/0344.反转字符串.md b/problems/0344.反转字符串.md index 9176c915..58bada05 100644 --- a/problems/0344.反转字符串.md +++ b/problems/0344.反转字符串.md @@ -200,6 +200,27 @@ var reverseString = function(s) { }; ``` +TypeScript: + +```typescript +/** + Do not return anything, modify s in-place instead. + */ +function reverseString(s: string[]): void { + let length: number = s.length; + let left: number = 0, + right: number = length - 1; + let tempStr: string; + while (left < right) { + tempStr = s[left]; + s[left] = s[right]; + s[right] = tempStr; + left++; + right--; + } +}; +``` + Swift: ```swift @@ -232,6 +253,19 @@ void reverseString(char* s, int sSize){ } ``` +C#: +```csharp +public class Solution +{ + public void ReverseString(char[] s) + { + for (int i = 0, j = s.Length - 1; i < j; i++, j--) + { + (s[i], s[j]) = (s[j], s[i]); + } + } +} +``` -----------------------
diff --git a/problems/0494.目标和.md b/problems/0494.目标和.md index 1835f498..0faef4a5 100644 --- a/problems/0494.目标和.md +++ b/problems/0494.目标和.md @@ -289,7 +289,7 @@ func findTargetSumWays(nums []int, target int) int { for _, v := range nums { sum += v } - if target > sum { + if abs(target) > sum { return 0 } if (sum+target)%2 == 1 { @@ -311,49 +311,12 @@ func findTargetSumWays(nums []int, target int) int { } return dp[bag] } -``` -> 更新版,上一个跑不通了,因为会存在bag 小于0的情况 -```go -func findTargetSumWays(nums []int, target int) int { - //先转化为数学问题 - //a-b=target - //a+b=sum - //a=(target+sum)/2 - //求出sum - var sum int - for _,value:=range nums{ - sum+=value - } - //如果sum { diff --git a/problems/0541.反转字符串II.md b/problems/0541.反转字符串II.md index fb92b1e4..14b8601a 100644 --- a/problems/0541.反转字符串II.md +++ b/problems/0541.反转字符串II.md @@ -252,6 +252,28 @@ var reverseStr = function(s, k) { ``` +TypeScript: + +```typescript +function reverseStr(s: string, k: number): string { + let left: number, right: number; + let arr: string[] = s.split(''); + let temp: string; + for (let i = 0, length = arr.length; i < length; i += 2 * k) { + left = i; + right = (i + k - 1) >= length ? length - 1 : i + k - 1; + while (left < right) { + temp = arr[left]; + arr[left] = arr[right]; + arr[right] = temp; + left++; + right--; + } + } + return arr.join(''); +}; +``` + Swift: ```swift @@ -272,9 +294,21 @@ func reverseStr(_ s: String, _ k: Int) -> String { } ``` - - - +C#: +```csharp +public class Solution +{ + public string ReverseStr(string s, int k) + { + Span span = s.ToCharArray().AsSpan(); + for (int i = 0; i < span.Length; i += 2 * k) + { + span[i + k < span.Length ? i..(i + k) : i..].Reverse(); + } + return span.ToString(); + } +} +``` -----------------------
diff --git a/problems/0844.比较含退格的字符串.md b/problems/0844.比较含退格的字符串.md index 5d629a8c..00d52e42 100644 --- a/problems/0844.比较含退格的字符串.md +++ b/problems/0844.比较含退格的字符串.md @@ -205,6 +205,42 @@ class Solution: return self.get_string(s) == self.get_string(t) pass ``` +双指针 +```python +class Solution: + def backspaceCompare(self, s: str, t: str) -> bool: + s_index, t_index = len(s) - 1, len(t) - 1 + s_backspace, t_backspace = 0, 0 # 记录s,t的#数量 + while s_index >= 0 or t_index >= 0: # 使用or,以防长度不一致 + while s_index >= 0: # 从后向前,消除s的# + if s[s_index] == '#': + s_index -= 1 + s_backspace += 1 + else: + if s_backspace > 0: + s_index -= 1 + s_backspace -= 1 + else: + break + while t_index >= 0: # 从后向前,消除t的# + if t[t_index] == '#': + t_index -= 1 + t_backspace += 1 + else: + if t_backspace > 0: + t_index -= 1 + t_backspace -= 1 + else: + break + if s_index >= 0 and t_index >= 0: # 后半部分#消除完了,接下来比较当前位的值 + if s[s_index] != t[t_index]: + return False + elif s_index >= 0 or t_index >= 0: # 一个字符串找到了待比较的字符,另一个没有,返回False + return False + s_index -= 1 + t_index -= 1 + return True +``` ### Go @@ -226,6 +262,51 @@ func backspaceCompare(s string, t string) bool { return getString(s) == getString(t) } +``` +双指针 +```go +func backspaceCompare(s string, t string) bool { + s_index, t_index := len(s) - 1, len(t) - 1 + s_backspace, t_backspace := 0, 0 // 记录s,t的#数量 + for s_index >= 0 || t_index >= 0 { // 使用or,以防长度不一致 + for s_index >= 0 { // 从后向前,消除s的# + if s[s_index] == '#' { + s_index-- + s_backspace++ + } else { + if s_backspace > 0 { + s_index-- + s_backspace-- + } else { + break + } + } + } + for t_index >= 0 { // 从后向前,消除t的# + if t[t_index] == '#' { + t_index-- + t_backspace++ + } else { + if t_backspace > 0 { + t_index-- + t_backspace-- + } else { + break + } + } + } + if s_index >= 0 && t_index >= 0 { // 后半部分#消除完了,接下来比较当前位的值 + if s[s_index] != t[t_index] { + return false + } + } else if s_index >= 0 || t_index >= 0 { // 一个字符串找到了待比较的字符,另一个没有,返回false + return false + } + s_index-- + t_index-- + } + return true +} ``` ### JavaScript diff --git a/problems/剑指Offer05.替换空格.md b/problems/剑指Offer05.替换空格.md index d0f382c8..530545fb 100644 --- a/problems/剑指Offer05.替换空格.md +++ b/problems/剑指Offer05.替换空格.md @@ -298,6 +298,33 @@ javaScript: }; ``` +TypeScript: + +```typescript +function replaceSpace(s: string): string { + let arr: string[] = s.split(''); + let spaceNum: number = 0; + let oldLength: number = arr.length; + for (let i = 0; i < oldLength; i++) { + if (arr[i] === ' ') { + spaceNum++; + } + } + arr.length = oldLength + 2 * spaceNum; + let cur: number = oldLength - 1; + for (let i = arr.length - 1; i >= 0; i--, cur--) { + if (arr[cur] !== ' ') { + arr[i] = arr[cur] + } else { + arr[i] = '0'; + arr[--i] = '2'; + arr[--i] = '%'; + } + } + return arr.join(''); +}; +``` + Swift: ```swift diff --git a/problems/剑指Offer58-II.左旋转字符串.md b/problems/剑指Offer58-II.左旋转字符串.md index c391d661..61391274 100644 --- a/problems/剑指Offer58-II.左旋转字符串.md +++ b/problems/剑指Offer58-II.左旋转字符串.md @@ -209,6 +209,61 @@ var reverseLeftWords = function(s, n) { }; ``` +版本二(在原字符串上操作): + +```js +/** + * @param {string} s + * @param {number} n + * @return {string} + */ +var reverseLeftWords = function (s, n) { + /** Utils */ + function reverseWords(strArr, start, end) { + let temp; + while (start < end) { + temp = strArr[start]; + strArr[start] = strArr[end]; + strArr[end] = temp; + start++; + end--; + } + } + /** Main code */ + let strArr = s.split(''); + let length = strArr.length; + reverseWords(strArr, 0, length - 1); + reverseWords(strArr, 0, length - n - 1); + reverseWords(strArr, length - n, length - 1); + return strArr.join(''); +}; +``` + +TypeScript: + +```typescript +function reverseLeftWords(s: string, n: number): string { + /** Utils */ + function reverseWords(strArr: string[], start: number, end: number): void { + let temp: string; + while (start < end) { + temp = strArr[start]; + strArr[start] = strArr[end]; + strArr[end] = temp; + start++; + end--; + } + } + /** Main code */ + let strArr: string[] = s.split(''); + let length: number = strArr.length; + reverseWords(strArr, 0, length - 1); + reverseWords(strArr, 0, length - n - 1); + reverseWords(strArr, length - n, length - 1); + return strArr.join(''); +}; +``` + Swift: ```swift diff --git a/problems/链表理论基础.md b/problems/链表理论基础.md index 109aa1ed..a4fefa2b 100644 --- a/problems/链表理论基础.md +++ b/problems/链表理论基础.md @@ -195,10 +195,20 @@ class ListNode { ``` Python: - +```python +class ListNode: + def __init__(self, val, next=None): + self.val = val + self.next = next +``` Go: - +```go +type ListNode struct { + Val int + Next *ListNode +} +```