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();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值