Merge pull request #1773 from juguagua/leetcode-modify-the-code-of-the-array

更新数组部分,0209.长度最小的子数组 python, js 代码
This commit is contained in:
程序员Carl
2022-11-23 10:02:25 +08:00
committed by GitHub
3 changed files with 36 additions and 59 deletions

View File

@ -199,21 +199,15 @@ Python
```python3
class Solution:
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
# 快指针遍历元素
fast = 0
# 慢指针记录位置
slow = 0
for fast in range(len(nums)):
if nums[fast] != val:
nums[slow] = nums[fast]
slow += 1
return slow
```

View File

@ -169,39 +169,18 @@ Python
```python
class Solution:
def minSubArrayLen(self, s: int, nums: List[int]) -> int:
# 定义一个无限大的数
res = float("inf")
Sum = 0
index = 0
for i in range(len(nums)):
Sum += nums[i]
res = float("inf") # 定义一个无限大的数
Sum = 0 # 滑动窗口数值之和
i = 0 # 滑动窗口起始位置
for j in range(len(nums)):
Sum += nums[j]
while Sum >= s:
res = min(res, i-index+1)
Sum -= nums[index]
index += 1
res = min(res, j-i+1)
Sum -= nums[i]
i += 1
return 0 if res == float("inf") else res
```
```python
# 滑动窗口
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 {
@ -232,22 +211,23 @@ func minSubArrayLen(target int, nums []int) int {
JavaScript:
```js
var minSubArrayLen = function(target, nums) {
// 长度计算一次
const len = nums.length;
let l = r = sum = 0,
res = len + 1; // 子数组最大不会超过自身
while(r < len) {
sum += nums[r++];
// 窗口滑动
let start, end
start = end = 0
let sum = 0
let len = nums.length
let ans = Infinity
while(end < len){
sum += nums[end];
while (sum >= target) {
// r始终为开区间 [l, r)
res = res < r - l ? res : r - l;
sum-=nums[l++];
ans = Math.min(ans, end - start + 1);
sum -= nums[start];
start++;
}
end++;
}
return res > len ? 0 : res;
return ans === Infinity ? 0 : ans
};
```

View File

@ -108,9 +108,12 @@ public:
// 如果index大于链表的长度则返回空
// 如果index小于0则置为0作为链表的新头节点。
void addAtIndex(int index, int val) {
if (index > _size || index < 0) {
if (index > _size) {
return;
}
if (index < 0) {
index = 0;
}
LinkedNode* newNode = new LinkedNode(val);
LinkedNode* cur = _dummyHead;
while(index--) {