Subarray with given sum

本题链接

Given an unsorted array A of size N of non-negative integers, find a continuous sub-array which adds to a given number S.

Input:
The first line of input contains an integer T denoting the number of test cases. Then T test cases follow. Each test case consists of two lines. The first line of each test case is N and S, where N is the size of array and S is the sum. The second line of each test case contains N space separated integers denoting the array elements.

Output:
For each testcase, in a new line, print the starting and ending positions(1 indexing) of first such occuring subarray from the left if sum equals to subarray, else print -1.

Constraints:

1 <= T <= 100

1 <= N <= 107

1 <= Ai <= 1010

Example:
Input:

2
5 12
1 2 3 7 5
10 15
1 2 3 4 5 6 7 8 9 10

Output:

2 4
1 5

观察可知,数据大小超出了int范围,故此处使用long。
具体思路:
累加,如果大于当前值,就一直从前减到小于当前值,再比较是否相同,相同则输出索引加1,不同则输出-1。

import java.util.Scanner;

public class FirstSubarray {
    public static void calculateSubarray(long[] arr, long targetNum) {
        long sum = 0L;
        int index = 0;

        for (int i = 0; i < arr.length; i++) {
            sum += (long)arr[i];

            while (sum > targetNum) {
                sum -= arr[index];
                index++;
            }

            if (sum == targetNum) {
                System.out.println((index + 1) + " " + (i + 1));
                return;
            }
        }

        System.out.println(-1);
    }

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        
        int dataAmount = input.nextInt();

        for (int i = 0; i < dataAmount; i++) {
            long[] arr = new long[input.nextInt()];
            long targetNum = Long.valueOf(input.next());

            for (int j = 0; j < arr.length; j++) {
                arr[j] = Long.valueOf(input.next());
            }

            calculateSubarray(arr, targetNum);
        }

        input.close();
    }
}

猜你喜欢

转载自blog.csdn.net/qq_42254247/article/details/105254627
今日推荐