Directory
LeetCode 977. Squares of a Sorted Array
Solution:
class Solution {
public int[] sortedSquares(int[] nums) {
int left = 0;
int right = nums.length - 1;
int[] res = new int[nums.length];
int index = nums.length - 1;
while(left <= right){
if(nums[left] * nums[left] > nums[right] * nums[right]){
res[index--] = nums[left] * nums[left];
left++;
}
else{
res[index--] = nums[right] * nums[right];
right--;
}
}
return res;
}
}
Thoughts:
- I adoped
Double Pointer Method
left
points to the start position.right
points to the end position.
- The maximum value of the square of the array elements must be at both ends of the array, impossible at the middle.
LeetCode 209. Minimum Size Subarray Sum
Solution:
class Solution {
public int minSubArrayLen(int target, int[] nums) {
int left = 0;
int sum = 0;
int res = Integer.MAX_VALUE;
for(int right = 0; right < nums.length; right++){
sum += nums[right];
while(sum >= target){
// length of subarray: right - left + 1
res = Integer.min(res, right - left + 1);
// change the start position
sum-=nums[left++];
}
}
return res == Integer.MAX_VALUE ? 0 : res;
}
}
Time Complexity:O(n)
Space Complexity:O(1)
Thoughts:
- We should adopt the
Slide Window Method
, which means constantly changing the start and end position of the subarray until we get the result. - In this question, we should clarify the following three points:
What is the content of the window?
- Minimum length contiguous subarray whose sum is larger than
target
- Minimum length contiguous subarray whose sum is larger than
How to change that start position?
- If the current window’s sum is larger than
target
, move forwardleft
pointer
- If the current window’s sum is larger than
How to change the end position?
- It’s the pointer that iterates the array, which is the for-loop index.
LeetCode 59. Spiral Matrix II
Solution:
class Solution {
public int[][] generateMatrix(int n) {
int[][] result = new int[n][n];
int start = 0; // start position of each loop
int count = 1; // define the number to fill
int i,j;
while(start < n>>1){
for(j = start; j < n-start-1; j++){
result[start][j] = count++;
}
for(i = start; i < n-start-1; i++){
result[i][j] = count++;
}
for(; j > start; j--){
result[i][j] = count++;
}
for(; i > start; i--){
result[i][j] = count++;
}
start++;
}
// If n is an odd number, we should assign a value to the center matrix.
if(n%2 == 1)
result[start][start] = count;
return result;
}
}
Thoughts:
- Follow the
loop invariant
andleft-closed right-opened
principles when drawing each side. - Drawing the matrix
clockwise
:- fill the row above from left to right
- fill the right column from top to bottom
- fill the row below from right to left
- fill the left column from bottom to top
- If
n
is an odd number, we should assign a value to the center matrix.