two-point method
1.4 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.
two-pointer solution
the key point of this question is that the square of the elements at both ends of the array will be greater than that in the middle.
public static int[] sortedSquares(int[] nums) {
int[] sortSqArr = new int[nums.length];
int left = 0;
int right = nums.length-1;
int pointer = nums.length-1;
while(left <= right){
if(nums[left]*nums[left] < nums[right]*nums[right]){
sortSqArr[pointer--] = nums[right]*nums[right];
right--;
}else{
sortSqArr[pointer--] = nums[left]*nums[left];
left++;
}
}
return sortSqArr;
}
sliding window
1.5 209. Minimum Size Subarray Sum(sliding window)
Given an array of positive integers nums and a positive integer target, return the minimal length of a
subarray whose sum is greater than or equal to target. If there is no such subarray, return 0 instead.
Sliding window, essentially a two-pointer solution, used in solving array or string subsequence problems, such as finding the longest substring without repeating characters, maximum subarray sum,etc.
the key point of sliding window is to move the start position.
int start = 0;
int sum = 0;
int result = nums.length + 1;
for (int i = 0; i < nums.length; i++) {
sum += nums[i];
while(sum >= target){
// int length = i - start + 1;
// result = Math.min(length,result);
//simplify:
result = Math.min(i-start+1,result);
sum -= nums[start];
start++;
}
}
// if(result == nums.length + 1) return 0;
// else return result;
//simplify:
return result == nums.length + 1 ? 0:result;
模拟行为
1.6 59. Spiral Matrix II
Given a positive integer n, generate an n x n matrix filled with elements from 1 to n2 in spiral order.