mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 02:53:31 +08:00
Merge branch 'master' of github.com:youngyangyang04/leetcode-master
This commit is contained in:
@ -523,6 +523,10 @@
|
||||
|
||||
[点此这里](https://github.com/youngyangyang04/leetcode-master/graphs/contributors)查看LeetCode-Master的所有贡献者。感谢他们补充了LeetCode-Master的其他语言版本,让更多的读者收益于此项目。
|
||||
|
||||
# Star 趋势
|
||||
|
||||
[](https://star-history.com/#youngyangyang04/leetcode-master&Date)
|
||||
|
||||
# 关于作者
|
||||
|
||||
大家好,我是程序员Carl,哈工大师兄,《代码随想录》作者,先后在腾讯和百度从事后端技术研发,CSDN博客专家。对算法和C++后端技术有一定的见解,利用工作之余重新刷leetcode。
|
||||
|
@ -183,28 +183,24 @@ class Solution {
|
||||
|
||||
Python:
|
||||
|
||||
```python
|
||||
```python3
|
||||
class Solution:
|
||||
"""双指针法
|
||||
时间复杂度:O(n)
|
||||
空间复杂度:O(1)
|
||||
"""
|
||||
|
||||
@classmethod
|
||||
def removeElement(cls, nums: List[int], val: int) -> int:
|
||||
fast = slow = 0
|
||||
|
||||
while fast < len(nums):
|
||||
|
||||
if nums[fast] != val:
|
||||
nums[slow] = nums[fast]
|
||||
slow += 1
|
||||
|
||||
# 当 fast 指针遇到要删除的元素时停止赋值
|
||||
# slow 指针停止移动, fast 指针继续前进
|
||||
fast += 1
|
||||
|
||||
return slow
|
||||
def removeElement(self, nums: List[int], val: int) -> int:
|
||||
if nums is None or len(nums)==0:
|
||||
return 0
|
||||
l=0
|
||||
r=len(nums)-1
|
||||
while l<r:
|
||||
while(l<r and nums[l]!=val):
|
||||
l+=1
|
||||
while(l<r and nums[r]==val):
|
||||
r-=1
|
||||
nums[l], nums[r]=nums[r], nums[l]
|
||||
print(nums)
|
||||
if nums[l]==val:
|
||||
return l
|
||||
else:
|
||||
return l+1
|
||||
```
|
||||
|
||||
|
||||
|
@ -685,7 +685,21 @@ class Solution {
|
||||
```
|
||||
|
||||
Python3:
|
||||
|
||||
```python
|
||||
//暴力解法:
|
||||
class Solution(object):
|
||||
def strStr(self, haystack, needle):
|
||||
"""
|
||||
:type haystack: str
|
||||
:type needle: str
|
||||
:rtype: int
|
||||
"""
|
||||
m,n=len(haystack),len(needle)
|
||||
for i in range(m):
|
||||
if haystack[i:i+n]==needle:
|
||||
return i
|
||||
return -1
|
||||
```
|
||||
```python
|
||||
// 方法一
|
||||
class Solution:
|
||||
|
@ -7,7 +7,8 @@
|
||||
|
||||
# 34. 在排序数组中查找元素的第一个和最后一个位置
|
||||
|
||||
[题目链接](https://leetcode.cn/problems/find-first-and-last-position-of-element-in-sorted-array/)
|
||||
[力扣链接](https://leetcode.cn/problems/find-first-and-last-position-of-element-in-sorted-array/)
|
||||
|
||||
|
||||
给定一个按照升序排列的整数数组 nums,和一个目标值 target。找出给定目标值在数组中的开始位置和结束位置。
|
||||
|
||||
|
@ -359,6 +359,36 @@ function permute(nums: number[]): number[][] {
|
||||
};
|
||||
```
|
||||
|
||||
### Rust
|
||||
|
||||
```Rust
|
||||
impl Solution {
|
||||
fn backtracking(result: &mut Vec<Vec<i32>>, path: &mut Vec<i32>, nums: &Vec<i32>, used: &mut Vec<bool>) {
|
||||
let len = nums.len();
|
||||
if path.len() == len {
|
||||
result.push(path.clone());
|
||||
return;
|
||||
}
|
||||
for i in 0..len {
|
||||
if used[i] == true { continue; }
|
||||
used[i] = true;
|
||||
path.push(nums[i]);
|
||||
Self::backtracking(result, path, nums, used);
|
||||
path.pop();
|
||||
used[i] = false;
|
||||
}
|
||||
}
|
||||
|
||||
pub fn permute(nums: Vec<i32>) -> Vec<Vec<i32>> {
|
||||
let mut result: Vec<Vec<i32>> = Vec::new();
|
||||
let mut path: Vec<i32> = Vec::new();
|
||||
let mut used = vec![false; nums.len()];
|
||||
Self::backtracking(&mut result, &mut path, &nums, &mut used);
|
||||
result
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### C
|
||||
|
||||
```c
|
||||
|
@ -144,7 +144,61 @@ var totalNQueens = function(n) {
|
||||
};
|
||||
```
|
||||
|
||||
TypeScript:
|
||||
|
||||
```typescript
|
||||
// 0-该格为空,1-该格有皇后
|
||||
type GridStatus = 0 | 1;
|
||||
function totalNQueens(n: number): number {
|
||||
let resCount: number = 0;
|
||||
const chess: GridStatus[][] = new Array(n).fill(0)
|
||||
.map(_ => new Array(n).fill(0));
|
||||
backTracking(chess, n, 0);
|
||||
return resCount;
|
||||
function backTracking(chess: GridStatus[][], n: number, startRowIndex: number): void {
|
||||
if (startRowIndex === n) {
|
||||
resCount++;
|
||||
return;
|
||||
}
|
||||
for (let j = 0; j < n; j++) {
|
||||
if (checkValid(chess, startRowIndex, j, n) === true) {
|
||||
chess[startRowIndex][j] = 1;
|
||||
backTracking(chess, n, startRowIndex + 1);
|
||||
chess[startRowIndex][j] = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
function checkValid(chess: GridStatus[][], i: number, j: number, n: number): boolean {
|
||||
// 向上纵向检查
|
||||
let tempI: number = i - 1,
|
||||
tempJ: number = j;
|
||||
while (tempI >= 0) {
|
||||
if (chess[tempI][tempJ] === 1) return false;
|
||||
tempI--;
|
||||
}
|
||||
// 斜向左上检查
|
||||
tempI = i - 1;
|
||||
tempJ = j - 1;
|
||||
while (tempI >= 0 && tempJ >= 0) {
|
||||
if (chess[tempI][tempJ] === 1) return false;
|
||||
tempI--;
|
||||
tempJ--;
|
||||
}
|
||||
// 斜向右上检查
|
||||
tempI = i - 1;
|
||||
tempJ = j + 1;
|
||||
while (tempI >= 0 && tempJ < n) {
|
||||
if (chess[tempI][tempJ] === 1) return false;
|
||||
tempI--;
|
||||
tempJ++;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
```
|
||||
|
||||
C
|
||||
|
||||
```c
|
||||
//path[i]为在i行,path[i]列上存在皇后
|
||||
int *path;
|
||||
|
@ -171,6 +171,30 @@ class Solution:
|
||||
|
||||
return res
|
||||
```
|
||||
|
||||
```python3
|
||||
class Solution:
|
||||
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
|
||||
r=len(matrix)
|
||||
if r == 0 or len(matrix[0])==0:
|
||||
return []
|
||||
c=len(matrix[0])
|
||||
res=matrix[0]
|
||||
|
||||
if r>1:
|
||||
for i in range (1,r):
|
||||
res.append(matrix[i][c-1])
|
||||
for j in range(c-2, -1, -1):
|
||||
res.append(matrix[r-1][j])
|
||||
if c>1:
|
||||
for i in range(r-2, 0, -1):
|
||||
res.append(matrix[i][0])
|
||||
|
||||
M=[]
|
||||
for k in range(1, r-1):
|
||||
e=matrix[k][1:-1]
|
||||
M.append(e)
|
||||
|
||||
return res+self.spiralOrder(M)
|
||||
```
|
||||
-----------------------
|
||||
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>
|
||||
|
@ -471,5 +471,73 @@ int canCompleteCircuit(int* gas, int gasSize, int* cost, int costSize){
|
||||
}
|
||||
```
|
||||
|
||||
### Scala
|
||||
|
||||
暴力解法:
|
||||
|
||||
```scala
|
||||
object Solution {
|
||||
def canCompleteCircuit(gas: Array[Int], cost: Array[Int]): Int = {
|
||||
for (i <- cost.indices) {
|
||||
var rest = gas(i) - cost(i)
|
||||
var index = (i + 1) % cost.length // index为i的下一个节点
|
||||
while (rest > 0 && i != index) {
|
||||
rest += (gas(index) - cost(index))
|
||||
index = (index + 1) % cost.length
|
||||
}
|
||||
if (rest >= 0 && index == i) return i
|
||||
}
|
||||
-1
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
贪心算法,方法一:
|
||||
|
||||
```scala
|
||||
object Solution {
|
||||
def canCompleteCircuit(gas: Array[Int], cost: Array[Int]): Int = {
|
||||
var curSum = 0
|
||||
var min = Int.MaxValue
|
||||
for (i <- gas.indices) {
|
||||
var rest = gas(i) - cost(i)
|
||||
curSum += rest
|
||||
min = math.min(min, curSum)
|
||||
}
|
||||
if (curSum < 0) return -1 // 情况1: gas的总和小于cost的总和,不可能到达终点
|
||||
if (min >= 0) return 0 // 情况2: 最小值>=0,从0号出发可以直接到达
|
||||
// 情况3: min为负值,从后向前看,能把min填平的节点就是出发节点
|
||||
for (i <- gas.length - 1 to 0 by -1) {
|
||||
var rest = gas(i) - cost(i)
|
||||
min += rest
|
||||
if (min >= 0) return i
|
||||
}
|
||||
-1
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
贪心算法,方法二:
|
||||
|
||||
```scala
|
||||
object Solution {
|
||||
def canCompleteCircuit(gas: Array[Int], cost: Array[Int]): Int = {
|
||||
var curSum = 0
|
||||
var totalSum = 0
|
||||
var start = 0
|
||||
for (i <- gas.indices) {
|
||||
curSum += (gas(i) - cost(i))
|
||||
totalSum += (gas(i) - cost(i))
|
||||
if (curSum < 0) {
|
||||
start = i + 1 // 起始位置更新
|
||||
curSum = 0 // curSum从0开始
|
||||
}
|
||||
}
|
||||
if (totalSum < 0) return -1 // 说明怎么走不可能跑一圈
|
||||
start
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
-----------------------
|
||||
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>
|
||||
|
@ -179,8 +179,27 @@ class Solution:
|
||||
index += 1
|
||||
return 0 if res==float("inf") else res
|
||||
```
|
||||
|
||||
|
||||
```python3
|
||||
#滑动窗口
|
||||
class Solution:
|
||||
def minSubArrayLen(self, target: int, nums: List[int]) -> int:
|
||||
if nums is None or len(nums)==0:
|
||||
return 0
|
||||
lenf=len(nums)+1
|
||||
total=0
|
||||
i=j=0
|
||||
while (j<len(nums)):
|
||||
total=total+nums[j]
|
||||
j+=1
|
||||
while (total>=target):
|
||||
lenf=min(lenf,j-i)
|
||||
total=total-nums[i]
|
||||
i+=1
|
||||
if lenf==len(nums)+1:
|
||||
return 0
|
||||
else:
|
||||
return lenf
|
||||
```
|
||||
Go:
|
||||
```go
|
||||
func minSubArrayLen(target int, nums []int) int {
|
||||
|
@ -218,59 +218,41 @@ class Solution {
|
||||
```python
|
||||
#数组模拟
|
||||
class Solution:
|
||||
def isPalindrome(self, head: ListNode) -> bool:
|
||||
length = 0
|
||||
tmp = head
|
||||
while tmp: #求链表长度
|
||||
length += 1
|
||||
tmp = tmp.next
|
||||
|
||||
result = [0] * length
|
||||
tmp = head
|
||||
index = 0
|
||||
while tmp: #链表元素加入数组
|
||||
result[index] = tmp.val
|
||||
index += 1
|
||||
tmp = tmp.next
|
||||
|
||||
i, j = 0, length - 1
|
||||
while i < j: # 判断回文
|
||||
if result[i] != result[j]:
|
||||
def isPalindrome(self, head: Optional[ListNode]) -> bool:
|
||||
list=[]
|
||||
while head:
|
||||
list.append(head.val)
|
||||
head=head.next
|
||||
l,r=0, len(list)-1
|
||||
while l<=r:
|
||||
if list[l]!=list[r]:
|
||||
return False
|
||||
i += 1
|
||||
j -= 1
|
||||
return True
|
||||
|
||||
l+=1
|
||||
r-=1
|
||||
return True
|
||||
|
||||
#反转后半部分链表
|
||||
class Solution:
|
||||
def isPalindrome(self, head: ListNode) -> bool:
|
||||
if head == None or head.next == None:
|
||||
return True
|
||||
slow, fast = head, head
|
||||
while fast and fast.next:
|
||||
pre = slow
|
||||
slow = slow.next
|
||||
fast = fast.next.next
|
||||
|
||||
pre.next = None # 分割链表
|
||||
cur1 = head # 前半部分
|
||||
cur2 = self.reverseList(slow) # 反转后半部分,总链表长度如果是奇数,cur2比cur1多一个节点
|
||||
while cur1:
|
||||
if cur1.val != cur2.val:
|
||||
return False
|
||||
cur1 = cur1.next
|
||||
cur2 = cur2.next
|
||||
return True
|
||||
def isPalindrome(self, head: Optional[ListNode]) -> bool:
|
||||
fast = slow = head
|
||||
|
||||
def reverseList(self, head: ListNode) -> ListNode:
|
||||
cur = head
|
||||
pre = None
|
||||
while(cur!=None):
|
||||
temp = cur.next # 保存一下cur的下一个节点
|
||||
cur.next = pre # 反转
|
||||
pre = cur
|
||||
cur = temp
|
||||
return pre
|
||||
# find mid point which including (first) mid point into the first half linked list
|
||||
while fast and fast.next:
|
||||
fast = fast.next.next
|
||||
slow = slow.next
|
||||
node = None
|
||||
|
||||
# reverse second half linked list
|
||||
while slow:
|
||||
slow.next, slow, node = node, slow.next, slow
|
||||
|
||||
# compare reversed and original half; must maintain reversed linked list is shorter than 1st half
|
||||
while node:
|
||||
if node.val != head.val:
|
||||
return False
|
||||
node = node.next
|
||||
head = head.next
|
||||
return True
|
||||
```
|
||||
|
||||
### Go
|
||||
|
@ -213,6 +213,7 @@ public:
|
||||
if (abs(S) > sum) return 0; // 此时没有方案
|
||||
if ((S + sum) % 2 == 1) return 0; // 此时没有方案
|
||||
int bagSize = (S + sum) / 2;
|
||||
if (bagsize < 0) return 0;
|
||||
vector<int> dp(bagSize + 1, 0);
|
||||
dp[0] = 1;
|
||||
for (int i = 0; i < nums.size(); i++) {
|
||||
|
@ -262,10 +262,10 @@ class Solution {
|
||||
if (root1 == null) return root2;
|
||||
if (root2 == null) return root1;
|
||||
|
||||
TreeNode newRoot = new TreeNode(root1.val + root2.val);
|
||||
newRoot.left = mergeTrees(root1.left,root2.left);
|
||||
newRoot.right = mergeTrees(root1.right,root2.right);
|
||||
return newRoot;
|
||||
root1.val += root2.val;
|
||||
root1.left = mergeTrees(root1.left,root2.left);
|
||||
root1.right = mergeTrees(root1.right,root2.right);
|
||||
return root1;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
@ -220,19 +220,21 @@ class Solution:
|
||||
|
||||
(版本二)左闭右开区间
|
||||
|
||||
```python
|
||||
class Solution:
|
||||
```class Solution:
|
||||
def search(self, nums: List[int], target: int) -> int:
|
||||
left,right =0, len(nums)
|
||||
while left < right:
|
||||
mid = (left + right) // 2
|
||||
if nums[mid] < target:
|
||||
left = mid+1
|
||||
elif nums[mid] > target:
|
||||
right = mid
|
||||
if nums is None or len(nums)==0:
|
||||
return -1
|
||||
l=0
|
||||
r=len(nums)-1
|
||||
while (l<=r):
|
||||
m = round(l+(r-l)/2)
|
||||
if nums[m] == target:
|
||||
return m
|
||||
elif nums[m] > target:
|
||||
r=m-1
|
||||
else:
|
||||
return mid
|
||||
return -1
|
||||
l=m+1
|
||||
return -1
|
||||
```
|
||||
|
||||
**Go:**
|
||||
|
@ -129,29 +129,21 @@ class Solution {
|
||||
```
|
||||
### Python
|
||||
```python
|
||||
class Solution:
|
||||
def isLongPressedName(self, name: str, typed: str) -> bool:
|
||||
i, j = 0, 0
|
||||
m, n = len(name) , len(typed)
|
||||
while i< m and j < n:
|
||||
if name[i] == typed[j]: # 相同时向后匹配
|
||||
i += 1
|
||||
j += 1
|
||||
else: # 不相同
|
||||
if j == 0: return False # 如果第一位不相同,直接返回false
|
||||
# 判断边界为n-1,若为n会越界,例如name:"kikcxmvzi" typed:"kiikcxxmmvvzzz"
|
||||
while j < n - 1 and typed[j] == typed[j-1]: j += 1
|
||||
if name[i] == typed[j]:
|
||||
i += 1
|
||||
j += 1
|
||||
else: return False
|
||||
# 说明name没有匹配完
|
||||
if i < m: return False
|
||||
# 说明type没有匹配完
|
||||
while j < n:
|
||||
if typed[j] == typed[j-1]: j += 1
|
||||
else: return False
|
||||
return True
|
||||
i = j = 0
|
||||
while(i<len(name) and j<len(typed)):
|
||||
# If the current letter matches, move as far as possible
|
||||
if typed[j]==name[i]:
|
||||
while j+1<len(typed) and typed[j]==typed[j+1]:
|
||||
j+=1
|
||||
# special case when there are consecutive repeating letters
|
||||
if i+1<len(name) and name[i]==name[i+1]:
|
||||
i+=1
|
||||
else:
|
||||
j+=1
|
||||
i+=1
|
||||
else:
|
||||
return False
|
||||
return i == len(name) and j==len(typed)
|
||||
```
|
||||
|
||||
### Go
|
||||
|
@ -41,6 +41,15 @@ public:
|
||||
}
|
||||
};
|
||||
```
|
||||
```python3
|
||||
class Solution:
|
||||
def sortedSquares(self, nums: List[int]) -> List[int]:
|
||||
res=[]
|
||||
for num in nums:
|
||||
res.append(num**2)
|
||||
return sorted(res)
|
||||
```
|
||||
|
||||
|
||||
这个时间复杂度是 O(n + nlogn), 可以说是O(nlogn)的时间复杂度,但为了和下面双指针法算法时间复杂度有鲜明对比,我记为 O(n + nlog n)。
|
||||
|
||||
|
@ -289,6 +289,28 @@ function largestSumAfterKNegations(nums: number[], k: number): number {
|
||||
};
|
||||
```
|
||||
|
||||
### Scala
|
||||
|
||||
```scala
|
||||
object Solution {
|
||||
def largestSumAfterKNegations(nums: Array[Int], k: Int): Int = {
|
||||
var num = nums.sortWith(math.abs(_) > math.abs(_))
|
||||
|
||||
var kk = k // 因为k是不可变量,所以要赋值给一个可变量
|
||||
for (i <- num.indices) {
|
||||
if (num(i) < 0 && kk > 0) {
|
||||
num(i) *= -1 // 取反
|
||||
kk -= 1
|
||||
}
|
||||
}
|
||||
|
||||
// kk对2取余,结果为0则为偶数不需要取反,结果为1为奇数,只需要对最后的数字进行反转就可以
|
||||
if (kk % 2 == 1) num(num.size - 1) *= -1
|
||||
|
||||
num.sum // 最后返回数字的和
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
|
||||
|
@ -108,7 +108,7 @@ https://github.com/youngyangyang04/fileHttpServer
|
||||
|
||||
如果你有一个服务器,那就是独立的一台电脑,你怎么霍霍就怎么霍霍,而且一年都不用关机的,可以一直跑你的任务,和你本地电脑也完全隔离。
|
||||
|
||||
更方便的是,你目前系统假如是centos,想做一个实验需要在unbantu上,如果是云服务器,更换系统就是在 后台点一下,一键重装,云厂商基本都是支持所有系统一件安装的。
|
||||
更方便的是,你目前系统假如是CentOS,想做一个实验需要在Ubuntu上,如果是云服务器,更换系统就是在 后台点一下,一键重装,云厂商基本都是支持所有系统一件安装的。
|
||||
|
||||
我们平时自己玩linux经常是配各种环境,然后这个linux就被自己玩坏了(一般都是毫无节制使用root权限导致的),总之就是环境配不起来了,基本就要重装了。
|
||||
|
||||
|
@ -160,6 +160,8 @@ class Solution:
|
||||
那么,只要其中一个链表走完了,就去走另一条链表的路。如果有交点,他们最终一定会在同一个
|
||||
位置相遇
|
||||
"""
|
||||
if headA is None or headB is None:
|
||||
return None
|
||||
cur_a, cur_b = headA, headB # 用两个指针代替a和b
|
||||
|
||||
|
||||
|
Reference in New Issue
Block a user