首先是第一题,977.有序数组的平方:
暴力解法:
class Solution {
public int[] sortedSquares(int[] nums) {
int n =nums.length;
int[] ans = new int[n];
for(int i =0;i<n;i++){
ans[i] = nums[i]*nums[i];
}
Arrays.sort(ans);
return ans;
}
}
看看题解,确实想不到这样的题可以用双指针
class Solution {
public int[] sortedSquares(int[] nums) {
int n =nums.length;
int[] ans = new int[n];
int l =0;
int r = n-1;
int j =n-1;
while(l<=r){
if(nums[l]*nums[l]>nums[r]*nums[r]){
ans[j] = nums[l]*nums[l];
l++;
}else{
ans[j] = nums[r]*nums[r];
r--;
}
j--;
}
return ans;
}
}
20.长度最小的子数组
先自己想:
超时写法(19/20)
import java.util.*;
class Solution {
public int minSubArrayLen(int target, int[] nums) {
int n = nums.length;
int all = nums[n-1];
int ans = Integer.MAX_VALUE;
if(nums[n-1]>=target)return 1;
for(int i =0;i<n-1;i++){
int tar = nums[i];
all += nums[i];
if(tar>=target){
ans = 1;
break;
}
for(int j = i+1;j<n;j++ ){
tar += nums[j];
if(tar>=target){
ans = Math.min(ans,j+1-i);
break;
}
}
}
if(all<target)ans=0;
return ans;
}
}
双指针
class Solution {
public int minSubArrayLen(int target, int[] nums) {
int n = nums.length;
int l =0;
int result = Integer.MAX_VALUE;
int sum =0;
for(int i = 0;i<n;i++){
sum += nums[i];
while(sum>=target){
result = result <i-l+1 ?result:i-l+1;
sum -= nums[l];
l++;
}
}
return result == Integer.MAX_VALUE?0:result;
}
}
59.螺旋矩阵
大模拟,不熟练,偶尔还得回头看看(回头重刷)
class Solution {
public int[][] generateMatrix(int n) {
int[][] ans = new int[n][n];
int num =1;
int left = 0;
int right =n-1;
int top =0;
int bottom =n-1;
while(left<=right&&top<=bottom){
for(int column = left;column<=right;column++){
ans[top][column] = num;
num++;
}
for(int row = top+1;row<=bottom;row++){
ans[row][right]=num;
num++;
}
if(left<right&& top<bottom){
for(int column = right-1;column>left;column--){
ans[bottom][column] = num;
num++;
}
for(int row = bottom;row>top;row--){
ans[row][left]=num;
num++;
}
}
left++;
right--;
top++;
bottom--;
}
return ans;
}
}