Training camp day 2 | Wed | Sep 21
Today's Algorithm:
- Double pointer method
- Sliding window method
ARRAY-数组
Leetcode 977. Squares of a Sorted Array
Given an integer array
nums
sorted in non-decreasing order, return an array of the squares of each number sorted in non-decreasing order.
Thought:
- The maximum value of the array square is on both ends of the array, not the far left or the right.
class Solution {
public int[] sortedSquares(int[] nums) {
int left = 0;
int right = nums.length - 1;
int[] result = new int[nums.length];
int index = result.length - 1;
while (left <= right){
if(nums[left] * nums[left] > nums[right] * nums[right]){
result[index--] = nums[left] * nums[left];
left++;
} else {
result[index--] = nums[right] * nums[right];
right--;
}
}
return result;
}
}
Leetcode 209. Minimum Size Subarray Sum
Given an array of positive integers
nums
and a positive integertarget
, return the minimal length of a contiguous subarray[numsl, numsl+1, ..., numsr-1, numsr]
of which the sum is greater than or equal totarget
. If there is no such subarray, return0
instead.
Thought:
- contiguous subarray
- The sliding window method is the starting position and termination position of the continuous adjustment of the subsequent sequence, so as to draw the results we want
- Note that the array cannot overflow
class Solution {
public int minSubArrayLen(int target, int[] nums) {
int sum = 0;
int left = 0;
int length = Integer.MAX_VALUE;
for(int right = 0; right < nums.length; right++){
sum += nums[right];
while (sum >= target) {
length = Math.min(length, right - left + 1);
sum -= nums[left++];
}
}
return length == Integer.MAX_VALUE ? 0 : length;
}
}
Leetcode 59. Spiral Matrix II
Given a positive integer
n
, generate ann x n
matrix
filled with elements from1
ton2
in spiral order.
Thought:
- No thoughts😭 Need to determine the constant value.
class Solution {
public int[][] generateMatrix(int n) {
int[][] arr=new int[n][n];
int e=1;
int minR=0;
int minC=0;
int maxR=n-1;
int maxC=n-1;
int count=0;
while(count<n*n){
//first fill the element in the top wall
//here row will remain the same
//column will change
for(int j=minC;j<=maxC && count<n*n;j++){
arr[minR][j]=e++;
count++;
}
minR=minR+1;
//now the element in the right wall
//here the colum will remain the same
//row will increase
for(int i=minR;i<=maxR && count<n*n;i++){
arr[i][maxC]=e;
e=e+1;
count++;
}
maxC=maxC-1;
//now printing the bottom wall
//here row will remain the same
//column will decrease
for(int j=maxC;j>=minC && count<n*n;j--){
arr[maxR][j]=e;
e=e+1;
count++;
}
maxR=maxR-1;
//now printing the left wall
//here column will remain the same
//rows will decrease
for(int i=maxR;i>=minR && count<n*n;i--){
arr[i][minC]=e;
e=e+1;
count++;
}
minC=minC+1;
}
return arr;
}
}