数组算法基础训练
class Solution {
public int minSubArrayLen(int target, int[] nums) {
int left = 0;
int sum = 0;
int result = Integer.MAX_VALUE;
for (int right = 0; right < nums.length; right ++){
sum += nums[right];
while(sum >= target){
result = Math.min(result, right - left + 1);
sum -= nums[left];
left ++;
}
}
return result == Integer.MAX_VALUE ? 0 : result;
}
}
class Solution {
public int[][] generateMatrix(int n) {
int[][] nums = new int[n][n];
int startX = 0;
int startY = 0;
int offset = 1;
int count = 1;
int i, j;
for(int a = 1; a <= (n>>1); a ++){
for(j = startY; j < n - offset; j ++){
nums[startX][j] = count;
count ++;
}
for(i = startX; i < n - offset; i ++){
nums[i][j] = count;
count ++;
}
for( ; j > startY; j --){
nums[i][j] = count;
count ++;
}
for( ; i > startX; i -- ){
nums[i][j] = count;
count ++;
}
startY ++;
startX ++;
offset ++;
}
if (n % 2 == 1){
nums[startX][startY] = count;
}
return nums;
}
}
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int sum = 0;
int[] prefix_sum = new int[n];
for (int i = 0; i < n; i++) {
int nextInt = sc.nextInt();
sum += nextInt;
prefix_sum[i] = sum;
}
while (sc.hasNextInt()){
int a = sc.nextInt();
int b = sc.nextInt();
if(a != 0){
System.out.println(prefix_sum[b] - prefix_sum[a - 1]);
}else{
System.out.println(prefix_sum[b]);
}
}
}
}
import java.util.Scanner;
public class Main{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
int sum_row = 0;
int[] row = new int[n];
int[] line = new int[m];
for (int i = 0; i < n; i ++){
for (int j = 0; j < m; j ++){
int nextInt = sc.nextInt();
line[j] += nextInt;
sum_row += nextInt;
}
row[i] = sum_row;
}
for (int j = 0; j < m; j++){
if(j == 0){
line[j] = line[j];
}else{
line[j] = line[j] + line[j - 1];
}
}
int result = Integer.MAX_VALUE;
for (int i = 0; i < n-1; i ++){
result = Math.min(result, Math.abs(row[n-1]-row[i]-row[i]));
}
for (int j = 0; j < m-1; j++){
result = Math.min(result,Math.abs(line[m-1]-line[j]-line[j]));
}
System.out.println(result);
sc.close();
}
}