有序數(shù)組的平方
題目鏈接
https://programmercarl.com/0977.%E6%9C%89%E5%BA%8F%E6%95%B0%E7%BB%84%E7%9A%84%E5%B9%B3%E6%96%B9.html
思路
我的想法是雙指針蚓再,兩側(cè)向中間,找最小的元素包各,但其實(shí)是找不到最小的元素摘仅,只能找到最大的元素,所以新數(shù)組需要倒著填充
public int[] sortedSquares(int[] nums) {
int left = 0, right = nums.length - 1, i = nums.length - 1;
int[] res = new int[nums.length];
while (left <= right) {
if (Math.abs(nums[left]) > Math.abs(nums[right])) {
res[i--] = nums[left] * nums[left++];
} else {
res[i--] = nums[right] * nums[right--];
}
}
return res;
}
長(zhǎng)度最小的子數(shù)組
題目鏈接
思路
滑動(dòng)窗口问畅,因?yàn)槭侨珵檎龜?shù)娃属,所以每累加一個(gè)元素一定會(huì)比之前的和大六荒。
右邊界滑動(dòng)直到和大于給定值,記錄長(zhǎng)度矾端,然后左邊界滑動(dòng)掏击,繼續(xù)循環(huán)。
public int minSubArrayLen(int target, int[] nums) {
int left = 0, right = 0, sum = 0, res = Integer.MAX_VALUE;
while (right < nums.length) {
sum += nums[right++];
while (sum >= target) {
res = Math.min(res, right - left);
sum -= nums[left++];
}
right++;
}
return res;
// return res == Integer.MAX_VALUE ? 0 : res;
}
螺旋矩陣
題目鏈接
https://programmercarl.com/0059.%E8%9E%BA%E6%97%8B%E7%9F%A9%E9%98%B5II.html
思路
循環(huán)賦值秩铆,找準(zhǔn)邊界砚亭,左開(kāi)右閉,右邊界不做處理豺旬。
根據(jù)N是奇數(shù)還是偶數(shù)钠惩,需要特殊處理
public int[][] generateMatrix(int n) {
int count = 1, l = 0, start = 0, i = 0, j = 0;
int[][] res = new int[n][n];
while (l++ < n/2) {
for (j = start; j < n - l; j++) {
res[start][j] = count++;
}
for (i = start; i < n - l; i++) {
res[i][j] = count++;
}
for (;j >= l; j--) {
res[i][j] = count++;
}
for(;i >= l; i--) {
res[i][j] = count++;
}
start++;
}
if (n % 2 == 1) {
res[start][start] = count++;
}
return res;
}
自己寫(xiě)的有誤,主要是因?yàn)槊恳淮窝h(huán)起始位置沒(méi)有掌握好族阅,上面那一條數(shù)據(jù)的橫坐標(biāo)不能用i篓跛,因?yàn)槊垦h(huán)一次這個(gè)值會(huì)改變,而i還是初始的值坦刀,所以是有問(wèn)題的愧沟。看完卡哥代碼鲤遥,重新理解了下沐寺,改了下就好了