简体   繁体   中英

How to find an item in an array that sum of all values before that is a spcific value? (C++ and C#)

Assume that I have an array of integers with a specific size (say 1000)

I want to find the index of an item in this array, given the sum of all items in the array before this item (or including this item).

for example assume that I have the following array:

 int[] values={1,2,3,1,3,6,4,8,2,11}

Input value is 6, then I need to return the index 2 (zero based indexing for 3 in above example) and when given 10, I should return the index 4.

What is the fastest way to do this? in C++ and c#?

If you need to do it only once, then the naive way is also the fastest way: walk the array, and keep the running total. Once you reach the target sum, return the current index.

If you need to run multiple queries for different sums, create an array and set up sums in it, like this:

var sums = new int[values.Length];
sums[0] = values[0];
for (int i = 1 ; i < sums.Length ; i++) {
    sums[i] = sums[i-1] + values[i];
}

If all values are positive, you can run binary search on sums to get to the index in O(log(n)) .

learn BST, it's will the fastest algo for your problem:

http://en.wikipedia.org/wiki/Binary_search_tree

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