Day2:双指针,数组
同向双指针(力扣977)
感觉用Math.pow有点多此一举,而且返回类型还是double类型需要强制转换
class Solution {
public int[] sortedSquares(int[] nums) {
int n = nums.length;
for(int i =0;i<n;i++){
nums[i] = (int)Math.pow(nums[i],2);
}
int left = 0;
int right = n-1;
int[] num = new int[n];
int aus = n-1;
while(left<=right){
if(nums[right]>nums[left]){
num[aus] = nums[right];
right--;
}else{
num[aus] = nums[left];
left++;
}
aus--;
}
return num;
}
}
滑动窗口(力扣209)
就一句话:右边无脑滑,左边有条件收
class Solution {
public int minSubArrayLen(int target, int[] nums) {
int n = nums.length;
int left = 0,right = 0;
int aus = n+1;
int sum = 0;
for(;right<n;right++){
sum += nums[right];
while(sum>=target){
aus = Math.min(aus,right-left+1);
sum -=nums[left];
left++;
}
}
if(aus!=n+1) return aus;
return 0;
}
}
数组(力扣59)
最先想到的就是顺时针按左下右上顺序循环走,这种写法边界条件十分清晰好处理
class Solution {
public int[][] generateMatrix(int n) {
int[][] nums = new int[n][n];
int x = 0, y = 0;
int[] dx = new int[]{0,1,0,-1};
int[] dy = new int[]{1,0,-1,0};
int count = 0;
int aus = 1;
while(aus<=n*n){
nums[x][y] = aus;
aus++;
int newx = x + dx[count];
int newy = y + dy[count];
if(newx<0||newx>=n||newy<0||newy>=n||nums[newx][newy]!=0){
count = (count+1)%4;
}
x = x + dx[count];
y = y + dy[count];
}
return nums;
}
}
其次就是看了代码随想录的循环不变量的思想
class Solution {
public int[][] generateMatrix(int n) {
int loop = 0; // 控制循环次数
int[][] res = new int[n][n];
int start = 0; // 每次循环的开始点(start, start)
int count = 1; // 定义填充数字
int i, j;
while (loop++ < n / 2) { // 判断边界后,loop从1开始
// 模拟上侧从左到右
for (j = start; j < n - loop; j++) {
res[start][j] = count++;
}
// 模拟右侧从上到下
for (i = start; i < n - loop; i++) {
res[i][j] = count++;
}
// 模拟下侧从右到左
for (; j >= loop; j--) {
res[i][j] = count++;
}
// 模拟左侧从下到上
for (; i >= loop; i--) {
res[i][j] = count++;
}
start++;
}
if (n % 2 == 1) {
res[start][start] = count;
}
return res;
}
}
每日一题
挖个坑,参考了灵神的代码,但是灵神的能过,我的超时=-=
class Solution {
int[] arr1, arr2;
Map<Integer, Integer> memo[];
public int makeArrayIncreasing(int[] arr1, int[] arr2) {
this.arr1 = arr1;
this.arr2 = arr2;
int n = arr1.length;
Arrays.sort(arr2);//快排,以便二分查找
memo = new HashMap[n];
Arrays.setAll(memo, e -> new HashMap<>());
int aus = dfs(n-1, Integer.MAX_VALUE);
return aus < Integer.MAX_VALUE / 2 ? aus : -1;
}
int dfs(int i, int max){
if(i < 0) return 0;//设定边界条件
int aus = Integer.MAX_VALUE / 2;//除2,防止“换”中arr2[pow]) + 1造成溢出
if(memo[i].containsKey(max)) return memo[i].get(max);//已计算过,直接返回结果
//不换
if(arr1[i] < max) aus = dfs(i-1, arr1[i]);
//换
int pow = erfen(arr2, max) - 1;
if(pow > -1) aus = Math.min(aus, dfs(i-1, arr2[pow]) + 1);
memo[i].put(max, aus);//记忆化
return aus;
}
int erfen(int[] arr2, int target){
int left = 0, right = arr2.length;
while(left < right){
int mid = left + (right - left) / 2;
if(arr2[mid] > target){
mid = right;
}else{
mid = left + 1;
}
}
return left;
}
}