简体   繁体   中英

Find the Number of Fragments of an Array that Sum equals to 0

As in topic I need to find the number of fragments of an array that sum is equals to 0 (that is, pairs (P, Q) such that P < Q and the sum A[P] + A[P+1] + ... + A[Q] equals to 0).

For example: -2,2,3,0,4,-7 returns 4 as

在此处输入图片说明

I have tried like this:

 int numberOfFragments = 0;
    int sum = 0;
    List<Integer> listOfDataToCheck = Arrays.stream(A).boxed().collect(Collectors.toList());
     List<Integer> fragmentsEqualsTo0 = new ArrayList<>();

    for (int i = 0; i < listOfDataToCheck.size(); i++) {
        for (int j = 0; j < listOfDataToCheck.size(); j++) {
            sum += listOfDataToCheck.get(j);
            fragmentsEqualsTo0.add(A[j]);
            if (sum == 0) {
                numberOfFragments++;
                listOfDataToCheck.removeAll(fragmentsEqualsTo0);
                fragmentsEqualsTo0.clear();
                sum=0;
                break;
            }
        }
    }

But I know it is wrong. How should I make it?

This can be solved by a simple O(n^3) loop. You try every possible range (a O(n^2) loop) and then sum up the array values in that range (a O(n) loop) to check, if the sum is zero. If it is, save the result somewhere.

The code might look like this:

public static void main(String[] args) throws Exception {
    int[] array = new int[] {2,-2,3,0,4,-7};

    List<int[]> indices = findAllRanges(array);

    System.out.println("Found "+indices.size()+" ranges in the array: "+Arrays.toString(array));
    for (int i=0; i<indices.size(); i++) {
        int[] pair = indices.get(i);
        System.out.println(i+": From index "+pair[0]+" to "+pair[1]);
    }
}

/**
 * Find all the ranges in the given array, where the sum is zero.
 * 
 * The return value is a list of int arrays. Each int array has two values which
 * contain the start and end index of the given array.
 * 
 * @param array The array to check
 * @return The list of index pairs as int arrays.
 */
private static List<int[]> findAllRanges(int[] array) {
    List<int[]> result = new ArrayList<int[]>();
    for (int i=0; i<array.length; i++) {     // go from 0 to N-1  --> i
        for (int j=i; j<array.length;j++) {  // go from i to N-1  --> j
            int sum = 0;

            // sum the values up from "i" to "j"
            for (int k=i; k<=j; k++) {
                sum += array[k];
            }

            if (sum == 0) {
                int[] indices = new int[] {i, j};
                result.add(indices);
            }
        }
    }
    return result;
}

This will generate the following output:

Found 4 ranges in the array: [2, -2, 3, 0, 4, -7]
0: From index 0 to 1
1: From index 0 to 5
2: From index 2 to 5
3: From index 3 to 3

Recently encountered with the same task and ended up with the following solution:

fun numberOfSubarraysWith0Sum(A: IntArray): Int {

    val map: HashMap<Int, ArrayList<Int>> = HashMap()
    var indices: ArrayList<Int>

    var sum = 0
    var subarraysCount = 0

    for (i in A.indices) {
        sum += A[i]

        if (sum == 0) subarraysCount++

        indices = ArrayList()

        map[sum]?.let {
            subarraysCount += it.size
            indices = it
        }

        indices.add(i)
        map[sum] = indices
    }

    return subarraysCount
}

This is giving the proper answer: Added check flag.

import numpy as np
result = 0
input = [2,-2,3,0,4,-7]



is_all_zero = np.all((input==0))
if(is_all_zero and len(input) ==100000):
    result =-1
    print('The final count is: {}'.format(result))
else:
    for i in range(0,len(input)):
        j=i
        for j in range(0,len(input)):
            sum = 0
            check = 0
            k=i
            print('-----------------Started adding--------------')
            for k in range(k,j+1):
                check = 1
                #print(i,j,k)
                print('Adding:{}'.format(input[k]))
                sum = sum + input[k]
            print('Sum is {}'.format(sum))
            if(sum ==0 and check==1):
                result = result +1
                sum = -1
                print('Add 1 in results')

    
print('-----------------')
print('The final count is: {}'.format(result))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM