4、长度最小的子数组
滑动窗口
- 暴力解法时间复杂度:O(n^2)
- 滑动窗口时间复杂度:O(n)
class Solution {
public int minSubArrayLen(int target, int[] nums) {
int i = 0;
int sum = 0;
int minLen = nums.length + 1;
for (int j = 0; j < nums.length; j++) {
sum += nums[j];
while (sum >= target) {
minLen = Math.min(j - i + 1, minLen);
sum -= nums[i++];
}
}
return minLen == nums.length + 1 ? 0 : minLen;
}
}
5、螺旋矩阵
class Solution {
public int[][] generateMatrix(int n) {
int[][] ans = new int[n][n];
int startX = 0;
int startY = 0;
int offSet = 1;
int count = 1;
int loop = 1;
int i, j;
while(loop <= n / 2){
for(j = startY; j < n - offSet; j++){
ans[startX][j] = count;
count++;
}
for(i = startX; i < n - offSet; i++){
ans[i][j] = count;
count++;
}
while(j > startY){
ans[i][j] = count;
count++;
j--;
}
while(i > startX){
ans[i][j] = count;
count++;
i--;
}
loop++;
startX++;
startY++;
offSet++;
}
if(n % 2 == 1){
ans[startX][startY] = count;
}
return ans;
}
}
6、区间和
学习输入输出的写法(ACM)
前缀和,需要注意区间问题 sum = p[b] - p[a - 1]
public class ArrayTest7 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int[] vec = new int[n];
int[] p = new int[n];
int presum = 0;
for(int i = 0; i < n; i++){
vec[i] = scanner.nextInt();
presum += vec[i];
p[i] = presum;
}
while(scanner.hasNextInt()){
int a = scanner.nextInt();
int b = scanner.nextInt();
int sum;
if(a == 0){
sum = p[b];
} else {
sum = p[b] - p[a - 1];
}
System.out.println(sum);
}
scanner.close();
}
}
7、开发商购买土地
前缀和
public class ArrayTest8 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int m = scanner.nextInt();
int sum = 0;
int[][] vec = new int[n][m];
for(int i = 0; i < n; i++){
for(int j = 0; j < m; j++){
vec[i][j] = scanner.nextInt();
sum += vec[i][j];
}
}
int[] horizontal = new int[n];
for(int i = 0; i < n; i++){
for(int j = 0; j < m; j++){
horizontal[i] += vec[i][j];
}
}
int[] vertical = new int[m];
for(int j = 0; j < m; j++){
for(int i = 0; i < n; i++){
vertical[j] += vec[i][j];
}
}
int result = Integer.MAX_VALUE;
int horizontalCut = 0;
for(int i = 0; i < n; i++){
horizontalCut += horizontal[i];
result = Math.min(result, Math.abs(sum - 2 * horizontalCut));
}
int verticalCut = 0;
for (int j = 0; j < m; j++){
verticalCut += vertical[j];
result = Math.min(result, Math.abs(sum - 2 * verticalCut));
}
System.out.println(result);
scanner.close();
}
}