mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-10 04:06:51 +08:00
Merge branch 'youngyangyang04:master' into master
This commit is contained in:
@ -136,6 +136,21 @@ func twoSum(nums []int, target int) []int {
|
||||
}
|
||||
```
|
||||
|
||||
```go
|
||||
// 使用map方式解题,降低时间复杂度
|
||||
func twoSum(nums []int, target int) []int {
|
||||
m := make(map[int]int)
|
||||
for index, val := range nums {
|
||||
if preIndex, ok := m[target-val]; ok {
|
||||
return []int{preIndex, index}
|
||||
} else {
|
||||
m[val] = index
|
||||
}
|
||||
}
|
||||
return []int{}
|
||||
}
|
||||
```
|
||||
|
||||
Rust
|
||||
|
||||
```rust
|
||||
|
@ -141,16 +141,7 @@ Java:
|
||||
class Solution {
|
||||
public int[][] merge(int[][] intervals) {
|
||||
List<int[]> res = new LinkedList<>();
|
||||
Arrays.sort(intervals, new Comparator<int[]>() {
|
||||
@Override
|
||||
public int compare(int[] o1, int[] o2) {
|
||||
if (o1[0] != o2[0]) {
|
||||
return Integer.compare(o1[0],o2[0]);
|
||||
} else {
|
||||
return Integer.compare(o1[1],o2[1]);
|
||||
}
|
||||
}
|
||||
});
|
||||
Arrays.sort(intervals, (o1, o2) -> Integer.compare(o1[0], o2[0]));
|
||||
|
||||
int start = intervals[0][0];
|
||||
for (int i = 1; i < intervals.length; i++) {
|
||||
|
@ -363,6 +363,54 @@ Python:
|
||||
|
||||
Go:
|
||||
|
||||
```go
|
||||
/**
|
||||
* Definition for a binary tree node.
|
||||
* type TreeNode struct {
|
||||
* Val int
|
||||
* Left *TreeNode
|
||||
* Right *TreeNode
|
||||
* }
|
||||
*/
|
||||
// 递归
|
||||
func defs(left *TreeNode, right *TreeNode) bool {
|
||||
if left == nil && right == nil {
|
||||
return true;
|
||||
};
|
||||
if left == nil || right == nil {
|
||||
return false;
|
||||
};
|
||||
if left.Val != right.Val {
|
||||
return false;
|
||||
}
|
||||
return defs(left.Left, right.Right) && defs(right.Left, left.Right);
|
||||
}
|
||||
func isSymmetric(root *TreeNode) bool {
|
||||
return defs(root.Left, root.Right);
|
||||
}
|
||||
|
||||
// 迭代
|
||||
func isSymmetric(root *TreeNode) bool {
|
||||
var queue []*TreeNode;
|
||||
if root != nil {
|
||||
queue = append(queue, root.Left, root.Right);
|
||||
}
|
||||
for len(queue) > 0 {
|
||||
left := queue[0];
|
||||
right := queue[1];
|
||||
queue = queue[2:];
|
||||
if left == nil && right == nil {
|
||||
continue;
|
||||
}
|
||||
if left == nil || right == nil || left.Val != right.Val {
|
||||
return false;
|
||||
};
|
||||
queue = append(queue, left.Left, right.Right, right.Left, left.Right);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
JavaScript
|
||||
```javascript
|
||||
|
@ -284,6 +284,55 @@ Python:
|
||||
|
||||
Go:
|
||||
|
||||
```go
|
||||
/**
|
||||
* Definition for a binary tree node.
|
||||
* type TreeNode struct {
|
||||
* Val int
|
||||
* Left *TreeNode
|
||||
* Right *TreeNode
|
||||
* }
|
||||
*/
|
||||
func max (a, b int) int {
|
||||
if a > b {
|
||||
return a;
|
||||
}
|
||||
return b;
|
||||
}
|
||||
// 递归
|
||||
func maxDepth(root *TreeNode) int {
|
||||
if root == nil {
|
||||
return 0;
|
||||
}
|
||||
return max(maxDepth(root.Left), maxDepth(root.Right)) + 1;
|
||||
}
|
||||
|
||||
// 遍历
|
||||
func maxDepth(root *TreeNode) int {
|
||||
levl := 0;
|
||||
queue := make([]*TreeNode, 0);
|
||||
if root != nil {
|
||||
queue = append(queue, root);
|
||||
}
|
||||
for l := len(queue); l > 0; {
|
||||
for ;l > 0;l-- {
|
||||
node := queue[0];
|
||||
if node.Left != nil {
|
||||
queue = append(queue, node.Left);
|
||||
}
|
||||
if node.Right != nil {
|
||||
queue = append(queue, node.Right);
|
||||
}
|
||||
queue = queue[1:];
|
||||
}
|
||||
levl++;
|
||||
l = len(queue);
|
||||
}
|
||||
return levl;
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
|
||||
JavaScript
|
||||
```javascript
|
||||
|
@ -301,6 +301,64 @@ class Solution:
|
||||
|
||||
Go:
|
||||
|
||||
```go
|
||||
/**
|
||||
* Definition for a binary tree node.
|
||||
* type TreeNode struct {
|
||||
* Val int
|
||||
* Left *TreeNode
|
||||
* Right *TreeNode
|
||||
* }
|
||||
*/
|
||||
func min(a, b int) int {
|
||||
if a < b {
|
||||
return a;
|
||||
}
|
||||
return b;
|
||||
}
|
||||
// 递归
|
||||
func minDepth(root *TreeNode) int {
|
||||
if root == nil {
|
||||
return 0;
|
||||
}
|
||||
if root.Left == nil && root.Right != nil {
|
||||
return 1 + minDepth(root.Right);
|
||||
}
|
||||
if root.Right == nil && root.Left != nil {
|
||||
return 1 + minDepth(root.Left);
|
||||
}
|
||||
return min(minDepth(root.Left), minDepth(root.Right)) + 1;
|
||||
}
|
||||
|
||||
// 迭代
|
||||
|
||||
func minDepth(root *TreeNode) int {
|
||||
dep := 0;
|
||||
queue := make([]*TreeNode, 0);
|
||||
if root != nil {
|
||||
queue = append(queue, root);
|
||||
}
|
||||
for l := len(queue); l > 0; {
|
||||
dep++;
|
||||
for ; l > 0; l-- {
|
||||
node := queue[0];
|
||||
if node.Left == nil && node.Right == nil {
|
||||
return dep;
|
||||
}
|
||||
if node.Left != nil {
|
||||
queue = append(queue, node.Left);
|
||||
}
|
||||
if node.Right != nil {
|
||||
queue = append(queue, node.Right);
|
||||
}
|
||||
queue = queue[1:];
|
||||
}
|
||||
l = len(queue);
|
||||
}
|
||||
return dep;
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
JavaScript:
|
||||
|
||||
|
@ -318,9 +318,61 @@ class Solution {
|
||||
|
||||
Python:
|
||||
|
||||
|
||||
Go:
|
||||
|
||||
```go
|
||||
import (
|
||||
"fmt"
|
||||
)
|
||||
|
||||
func reverseWords(s string) string {
|
||||
//1.使用双指针删除冗余的空格
|
||||
slowIndex, fastIndex := 0, 0
|
||||
b := []byte(s)
|
||||
//删除头部冗余空格
|
||||
for len(b) > 0 && fastIndex < len(b) && b[fastIndex] == ' ' {
|
||||
fastIndex++
|
||||
}
|
||||
//删除单词间冗余空格
|
||||
for ; fastIndex < len(b); fastIndex++ {
|
||||
if fastIndex-1 > 0 && b[fastIndex-1] == b[fastIndex] && b[fastIndex] == ' ' {
|
||||
continue
|
||||
}
|
||||
b[slowIndex] = b[fastIndex]
|
||||
slowIndex++
|
||||
}
|
||||
//删除尾部冗余空格
|
||||
if slowIndex-1 > 0 && b[slowIndex-1] == ' ' {
|
||||
b = b[:slowIndex-1]
|
||||
} else {
|
||||
b = b[:slowIndex]
|
||||
}
|
||||
//2.反转整个字符串
|
||||
reverse(&b, 0, len(b)-1)
|
||||
//3.反转单个单词 i单词开始位置,j单词结束位置
|
||||
i := 0
|
||||
for i < len(b) {
|
||||
j := i
|
||||
for ; j < len(b) && b[j] != ' '; j++ {
|
||||
}
|
||||
reverse(&b, i, j-1)
|
||||
i = j
|
||||
i++
|
||||
}
|
||||
return string(b)
|
||||
}
|
||||
|
||||
func reverse(b *[]byte, left, right int) {
|
||||
for left < right {
|
||||
(*b)[left], (*b)[right] = (*b)[right], (*b)[left]
|
||||
left++
|
||||
right--
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@ -328,4 +380,4 @@ Go:
|
||||
* 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw)
|
||||
* B站视频:[代码随想录](https://space.bilibili.com/525438321)
|
||||
* 知识星球:[代码随想录](https://mp.weixin.qq.com/s/QVF6upVMSbgvZy8lHZS3CQ)
|
||||
<div align="center"><img src=../pics/公众号.png width=450 alt=> </img></div>
|
||||
<div align="center"><img src=../pics/公众号.png width=450 alt=> </img></div>
|
@ -263,6 +263,41 @@ class Solution {
|
||||
```
|
||||
|
||||
Python:
|
||||
```python
|
||||
class MyQueue: #单调队列(从大到小
|
||||
def __init__(self):
|
||||
self.queue = [] #使用list来实现单调队列
|
||||
|
||||
#每次弹出的时候,比较当前要弹出的数值是否等于队列出口元素的数值,如果相等则弹出。
|
||||
#同时pop之前判断队列当前是否为空。
|
||||
def pop(self, value):
|
||||
if self.queue and value == self.queue[0]:
|
||||
self.queue.pop(0)#list.pop()时间复杂度为O(n),这里可以使用collections.deque()
|
||||
|
||||
#如果push的数值大于入口元素的数值,那么就将队列后端的数值弹出,直到push的数值小于等于队列入口元素的数值为止。
|
||||
#这样就保持了队列里的数值是单调从大到小的了。
|
||||
def push(self, value):
|
||||
while self.queue and value > self.queue[-1]:
|
||||
self.queue.pop()
|
||||
self.queue.append(value)
|
||||
|
||||
#查询当前队列里的最大值 直接返回队列前端也就是front就可以了。
|
||||
def front(self):
|
||||
return self.queue[0]
|
||||
|
||||
class Solution:
|
||||
def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
|
||||
que = MyQueue()
|
||||
result = []
|
||||
for i in range(k): #先将前k的元素放进队列
|
||||
que.push(nums[i])
|
||||
result.append(que.front()) #result 记录前k的元素的最大值
|
||||
for i in range(k, len(nums)):
|
||||
que.pop(nums[i - k]) #滑动窗口移除最前面元素
|
||||
que.push(nums[i]) #滑动窗口前加入最后面的元素
|
||||
result.append(que.front()) #记录对应的最大值
|
||||
return result
|
||||
```
|
||||
|
||||
|
||||
Go:
|
||||
|
@ -162,7 +162,33 @@ class Solution {
|
||||
|
||||
|
||||
Python:
|
||||
|
||||
```python
|
||||
#时间复杂度:O(nlogk)
|
||||
#空间复杂度:O(n)
|
||||
import heapq
|
||||
class Solution:
|
||||
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
|
||||
#要统计元素出现频率
|
||||
map_ = {} #nums[i]:对应出现的次数
|
||||
for i in range(len(nums)):
|
||||
map_[nums[i]] = map_.get(nums[i], 0) + 1
|
||||
|
||||
#对频率排序
|
||||
#定义一个小顶堆,大小为k
|
||||
pri_que = [] #小顶堆
|
||||
|
||||
#用固定大小为k的小顶堆,扫面所有频率的数值
|
||||
for key, freq in map_.items():
|
||||
heapq.heappush(pri_que, (freq, key))
|
||||
if len(pri_que) > k: #如果堆的大小大于了K,则队列弹出,保证堆的大小一直为k
|
||||
heapq.heappop(pri_que)
|
||||
|
||||
#找出前K个高频元素,因为小顶堆先弹出的是最小的,所以倒叙来输出到数组
|
||||
result = [0] * k
|
||||
for i in range(k-1, -1, -1):
|
||||
result[i] = heapq.heappop(pri_que)[1]
|
||||
return result
|
||||
```
|
||||
|
||||
Go:
|
||||
|
||||
|
@ -166,6 +166,21 @@ class Solution(object):
|
||||
```
|
||||
|
||||
Go:
|
||||
```go
|
||||
func canConstruct(ransomNote string, magazine string) bool {
|
||||
record := make([]int, 26)
|
||||
for _, v := range magazine {
|
||||
record[v-'a']++
|
||||
}
|
||||
for _, v := range ransomNote {
|
||||
record[v-'a']--
|
||||
if record[v-'a'] < 0 {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
```
|
||||
|
||||
javaScript:
|
||||
|
||||
|
@ -154,6 +154,23 @@ class Solution(object):
|
||||
|
||||
|
||||
Go:
|
||||
```go
|
||||
func fourSumCount(nums1 []int, nums2 []int, nums3 []int, nums4 []int) int {
|
||||
m := make(map[int]int)
|
||||
count := 0
|
||||
for _, v1 := range nums1 {
|
||||
for _, v2 := range nums2 {
|
||||
m[v1+v2]++
|
||||
}
|
||||
}
|
||||
for _, v3 := range nums3 {
|
||||
for _, v4 := range nums4 {
|
||||
count += m[-v3-v4]
|
||||
}
|
||||
}
|
||||
return count
|
||||
}
|
||||
```
|
||||
|
||||
javaScript:
|
||||
|
||||
|
@ -184,6 +184,55 @@ class Solution {
|
||||
|
||||
Python:
|
||||
|
||||
这里使用了前缀表统一减一的实现方式
|
||||
|
||||
```python
|
||||
class Solution:
|
||||
def repeatedSubstringPattern(self, s: str) -> bool:
|
||||
if len(s) == 0:
|
||||
return False
|
||||
nxt = [0] * len(s)
|
||||
self.getNext(nxt, s)
|
||||
if nxt[-1] != -1 and len(s) % (len(s) - (nxt[-1] + 1)) == 0:
|
||||
return True
|
||||
return False
|
||||
|
||||
def getNext(self, nxt, s):
|
||||
nxt[0] = -1
|
||||
j = -1
|
||||
for i in range(1, len(s)):
|
||||
while j >= 0 and s[i] != s[j+1]:
|
||||
j = nxt[j]
|
||||
if s[i] == s[j+1]:
|
||||
j += 1
|
||||
nxt[i] = j
|
||||
return nxt
|
||||
```
|
||||
|
||||
前缀表(不减一)的代码实现
|
||||
|
||||
```python
|
||||
class Solution:
|
||||
def repeatedSubstringPattern(self, s: str) -> bool:
|
||||
if len(s) == 0:
|
||||
return False
|
||||
nxt = [0] * len(s)
|
||||
self.getNext(nxt, s)
|
||||
if nxt[-1] != 0 and len(s) % (len(s) - nxt[-1]) == 0:
|
||||
return True
|
||||
return False
|
||||
|
||||
def getNext(self, nxt, s):
|
||||
nxt[0] = 0
|
||||
j = 0
|
||||
for i in range(1, len(s)):
|
||||
while j > 0 and s[i] != s[j]:
|
||||
j = nxt[j - 1]
|
||||
if s[i] == s[j]:
|
||||
j += 1
|
||||
nxt[i] = j
|
||||
return nxt
|
||||
```
|
||||
|
||||
Go:
|
||||
|
||||
|
@ -276,7 +276,35 @@ class Solution:
|
||||
```
|
||||
|
||||
Go:
|
||||
|
||||
```go
|
||||
func findTargetSumWays(nums []int, target int) int {
|
||||
sum := 0
|
||||
for _, v := range nums {
|
||||
sum += v
|
||||
}
|
||||
if target > sum {
|
||||
return 0
|
||||
}
|
||||
if (sum+target)%2 == 1 {
|
||||
return 0
|
||||
}
|
||||
// 计算背包大小
|
||||
bag := (sum + target) / 2
|
||||
// 定义dp数组
|
||||
dp := make([]int, bag+1)
|
||||
// 初始化
|
||||
dp[0] = 1
|
||||
// 遍历顺序
|
||||
for i := 0; i < len(nums); i++ {
|
||||
for j := bag; j >= nums[i]; j-- {
|
||||
//推导公式
|
||||
dp[j] += dp[j-nums[i]]
|
||||
//fmt.Println(dp)
|
||||
}
|
||||
}
|
||||
return dp[bag]
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
|
||||
|
@ -191,7 +191,33 @@ class Solution:
|
||||
```
|
||||
|
||||
Go:
|
||||
```go
|
||||
func lastStoneWeightII(stones []int) int {
|
||||
// 15001 = 30 * 1000 /2 +1
|
||||
dp := make([]int, 15001)
|
||||
// 求target
|
||||
sum := 0
|
||||
for _, v := range stones {
|
||||
sum += v
|
||||
}
|
||||
target := sum / 2
|
||||
// 遍历顺序
|
||||
for i := 0; i < len(stones); i++ {
|
||||
for j := target; j >= stones[i]; j-- {
|
||||
// 推导公式
|
||||
dp[j] = max(dp[j], dp[j-stones[i]]+stones[i])
|
||||
}
|
||||
}
|
||||
return sum - 2 * dp[target]
|
||||
}
|
||||
|
||||
func max(a, b int) int {
|
||||
if a > b {
|
||||
return a
|
||||
}
|
||||
return b
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
|
||||
|
@ -239,7 +239,78 @@ Java:
|
||||
|
||||
```
|
||||
Python:
|
||||
> 迭代法前序遍历
|
||||
|
||||
```python
|
||||
class Solution:
|
||||
def preorderTraversal(self, root: TreeNode) -> List[int]:
|
||||
result = []
|
||||
st= []
|
||||
if root:
|
||||
st.append(root)
|
||||
while st:
|
||||
node = st.pop()
|
||||
if node != None:
|
||||
if node.right: #右
|
||||
st.append(node.right)
|
||||
if node.left: #左
|
||||
st.append(node.left)
|
||||
st.append(node) #中
|
||||
st.append(None)
|
||||
else:
|
||||
node = st.pop()
|
||||
result.append(node.val)
|
||||
return result
|
||||
```
|
||||
|
||||
> 迭代法中序遍历
|
||||
```python
|
||||
class Solution:
|
||||
def inorderTraversal(self, root: TreeNode) -> List[int]:
|
||||
result = []
|
||||
st = []
|
||||
if root:
|
||||
st.append(root)
|
||||
while st:
|
||||
node = st.pop()
|
||||
if node != None:
|
||||
if node.right: #添加右节点(空节点不入栈)
|
||||
st.append(node.right)
|
||||
|
||||
st.append(node) #添加中节点
|
||||
st.append(None) #中节点访问过,但是还没有处理,加入空节点做为标记。
|
||||
|
||||
if node.left: #添加左节点(空节点不入栈)
|
||||
st.append(node.left)
|
||||
else: #只有遇到空节点的时候,才将下一个节点放进结果集
|
||||
node = st.pop() #重新取出栈中元素
|
||||
result.append(node.val) #加入到结果集
|
||||
return result
|
||||
```
|
||||
|
||||
> 迭代法后序遍历
|
||||
```python
|
||||
class Solution:
|
||||
def postorderTraversal(self, root: TreeNode) -> List[int]:
|
||||
result = []
|
||||
st = []
|
||||
if root:
|
||||
st.append(root)
|
||||
while st:
|
||||
node = st.pop()
|
||||
if node != None:
|
||||
st.append(node) #中
|
||||
st.append(None)
|
||||
|
||||
if node.right: #右
|
||||
st.append(node.right)
|
||||
if node.left: #左
|
||||
st.append(node.left)
|
||||
else:
|
||||
node = st.pop()
|
||||
result.append(node.val)
|
||||
return result
|
||||
```
|
||||
|
||||
Go:
|
||||
> 前序遍历统一迭代法
|
||||
|
@ -23,7 +23,7 @@ https://leetcode-cn.com/problems/zuo-xuan-zhuan-zi-fu-chuan-lcof/
|
||||
示例 2:
|
||||
输入: s = "lrloseumgh", k = 6
|
||||
输出: "umghlrlose"
|
||||
|
||||
|
||||
限制:
|
||||
1 <= k < s.length <= 10000
|
||||
|
||||
@ -119,9 +119,31 @@ class Solution {
|
||||
```
|
||||
Python:
|
||||
|
||||
|
||||
Go:
|
||||
|
||||
```go
|
||||
func reverseLeftWords(s string, n int) string {
|
||||
b := []byte(s)
|
||||
// 1. 反转前n个字符
|
||||
// 2. 反转第n到end字符
|
||||
// 3. 反转整个字符
|
||||
reverse(b, 0, n-1)
|
||||
reverse(b, n, len(b)-1)
|
||||
reverse(b, 0, len(b)-1)
|
||||
return string(b)
|
||||
}
|
||||
// 切片是引用传递
|
||||
func reverse(b []byte, left, right int){
|
||||
for left < right{
|
||||
b[left], b[right] = b[right],b[left]
|
||||
left++
|
||||
right--
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@ -129,4 +151,4 @@ Go:
|
||||
* 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw)
|
||||
* B站视频:[代码随想录](https://space.bilibili.com/525438321)
|
||||
* 知识星球:[代码随想录](https://mp.weixin.qq.com/s/QVF6upVMSbgvZy8lHZS3CQ)
|
||||
<div align="center"><img src=../pics/公众号.png width=450 alt=> </img></div>
|
||||
<div align="center"><img src=../pics/公众号.png width=450 alt=> </img></div>
|
Reference in New Issue
Block a user