977.有序数组的平方
题目链接
题目难度
简单
看到题目以后的第一想法
遍历数组平方然后再排序
看完代码随想录之后的总
1.解题思路
双指针法,需要注意的是数组中可能存在负数,所以负数平方之后可能会变大。
2.文章讲解
3.视频讲解
代码实现
python
class Solution:
def sortedSquares(self, nums: List[int]) -> List[int]:
n = len(nums)
left, right = 0, n-1
res = [0] * n
index = n - 1
while(left <= right):
if nums[left]**2 >= nums[right]**2:
res[index] = nums[left]**2
left += 1
else:
res[index] = nums[right]**2
right -= 1
index -= 1
return res
Java
class Solution {
public int[] sortedSquares(int[] nums) {
int n = nums.length;
int left = 0;
int right = n-1;
int[] res = new int[n];
int index = n-1;
while(left <= right){
if(nums[left]*nums[left] >= nums[right] * nums[right]){
res[index] = nums[left]*nums[left];
left++;
}else{
res[index] = nums[right] * nums[right];
right--;
}
index--;
}
return res;
}
}
209.长度最小的子数组
题目链接
题目难度
中等
看到题目以后的第一想法
暴力解法
看完代码随想录之后的总结
1.解题思路
滑动窗口,就是不断的调节子序列的起始位置和终止位置;时间复杂度O(n),空间复杂度O(1)。
2.文章讲解
代码随想录长度最小的子数组
3.视频讲解
代码实现
python
class Solution:
def minSubArrayLen(self, target: int, nums: List[int]) -> int:
n = len(nums)
sum_num = 0
start = 0
end = 0
leng = float('inf')
while end < n:
sum_num += nums[end]
while start<=end and sum_num >= target:
leng = min(leng, end-start+1)
sum_num -= nums[start]
start += 1
end += 1
return leng if leng != float('inf') else 0
java
class Solution {
public int minSubArrayLen(int target, int[] nums) {
int left = 0;
int end = 0;
int n = nums.length;
int r = Integer.MAX_VALUE;
int sum = 0;
while(end < n){
sum += nums[end];
while(sum >= target){
r = Math.min(r, end-left+1);
sum -= nums[left];
left += 1;
}
end += 1;
}
return r == Integer.MAX_VALUE ? 0:r;
}
}
今日感悟
依然是刷过的题目,算法方面感觉还算熟悉,主打一个java的练习。