Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

前缀和优化版,设置前缀和数组长度为原数组长度+1 #2902

Open
Hydrion-Qlz opened this issue Feb 26, 2025 · 0 comments
Open

Comments

@Hydrion-Qlz
Copy link

关于前缀和的讲解的时候,可以将sum数组的size建为n+1,这样在计算区间和的时候可以直接通过 preSum[b + 1] - preSum[a]计算,省去了关于a==0的判断

原文链接:https://programmercarl.com/kamacoder/0058.%E5%8C%BA%E9%97%B4%E5%92%8C.html#%E6%80%9D%E8%B7%AF

优化后的代码

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int[] arr = new int[n];
        for (int i = 0; i < n; i++) {
            arr[i] = sc.nextInt();
        }

        int[] preSum = new int[n + 1];
        int sum = 0;
        for (int i = 1; i < preSum.length; i++) {
            sum += arr[i - 1];
            preSum[i] = sum;
        }

        while (sc.hasNext()) {
            int a = sc.nextInt();
            int b = sc.nextInt();
            
            System.out.println(preSum[b + 1] - preSum[a]);
        }

        sc.close();
    }
}

原代码

public class Main {
    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();
    }
}
@Hydrion-Qlz Hydrion-Qlz changed the title 前缀和优化版 前缀和优化版,设置前缀和数组长度为原数组长度+1 Feb 26, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants
@Hydrion-Qlz and others