Day2
977
解题思路
这里是首尾指针,首尾指针需要碰头才能算遍历完数组的数据
然后就是怎么把遍历后的数据,按照指定顺序放进去
以上就是难点了
import java.util.Arrays;
public class SortedSquares {
public static void main(String[] args) {
System.out.println(Arrays.toString(solute(new int[]{-7, -3, 2, 3, 11})));
}
/**
* 首尾指针的使用
* 首尾指针需要相碰,才是完全遍历完所有数据
*/
static int[] solute(int[] nums) {
// 慢指针从数组 nums[0] 开始
int s = 0;
// 快指针从数组 nums[nums.length -1] 开始
int f = nums.length - 1;
// 数组的角标,用来填充新数组
int n = nums.length - 1;
// 从大往小填
int[] list = new int[nums.length];
// s和f需要碰头
while (s <= f) {
if (Math.abs(nums[s]) >= Math.abs(nums[f])) {
list[n--] = nums[s] * nums[s];
s++;
} else {
list[n--] = nums[f] * nums[f];
f--;
}
}
return list;
}
}
209
解题思路
之前写过这道理,我感觉双指针能用while就用while,if判断有点折磨人
然后我的解题思路是 用左边界作while循环判断条件,然后不知道怎么用右边界终止循环的
导致debug了半天,然后模拟画图,最后解决了,终于知道哪个点break出去了
用左边终止循环,需要注意sum不能一直加,否则数组越界或者错误的时机break出去,导致区间过大
public class MinSubArrayLen2 {
public static void main(String[] args) {
System.out.println(minSubArrayLen(3, new int[]{1, 1, 1, 1, 1}));
}
/**
* 滑动窗口思想
* 实际上就是两个指针交替滑动
* 一种动态的控制窗口内的数据量方法
*/
static int minSubArrayLen(int target, int[] nums) {
//滑动窗口左边界
int l = 0;
//滑动窗口右边界
int r = 0;
int bound = nums.length - 1;
// 不断计算窗口里的值,获得窗口数据的总和
int sum = 0;
// 通过不断的和最大值比较,得到最小窗口的值
int min = Integer.MAX_VALUE;
while (l <= bound) {
if (sum < target) {
if (r <= bound) {
sum = sum + nums[r];
r++;
} else {
// 当r超过边界,且总和还小于目标值时,终止循环
break;
}
} else {
sum = sum - nums[l];
min = Math.min(min, (r - l));
l++;
}
}
return min == Integer.MAX_VALUE ? 0 : min;
}
}
59
解题思路
用模拟行为,造一个移动角色,用自增来控制行进距离,x y为人物坐标
给角色设置障碍物,不断压缩小人的行进路线
但是我这里有两个问题 1是没有考虑n=1的情况 2是当进入最后一点的时候没有人物匹配条件 我得跳出所有障碍物 给人物走最后一步
public class GenerateMatrix {
public static void main(String[] args) {
System.out.println(Arrays.deepToString(solute(4)));
solute(3);
}
static int[][] solute(int n) {
int[][] matrix = new int[n][n];
// 边界条件
int init = 1;
int num = n * n;
int top = 0;
int left = 0;
int right = n - 1;
int bottom = n - 1;
// 移动坐标
int x = 0;
int y = 0;
while (init <= num) {
if (n == 1) {
matrix[0][0] = 1;
return matrix;
}
if (x == top && y < right) {
matrix[x][y] = init;
init++;
y++;
if (y == right) top++;
} else if (y == right && x < bottom) {
matrix[x][y] = init;
init++;
x++;
if (x == bottom) right--;
} else if (x == bottom && y > left) {
matrix[x][y] = init;
init++;
y--;
if (y == left) bottom--;
} else if (y == left && x > top) {
matrix[x][y] = init;
init++;
x--;
if (x == top) left++;
} else {
matrix[x][y] = init++;
}
}
return matrix;
}
}