简体   繁体   English

如何在数组中找到一个所有值之和为特定值的项? (C ++和C#)

[英]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) 假设我有一个具有特定大小(例如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. 输入值为6,那​​么我需要返回索引2(在上面的示例中为3的从零开始的索引),当给定10时,我应该返回索引4。

What is the fastest way to do this? 最快的方法是什么? in C++ and c#? 在C ++和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)) . 如果所有值都是正数,则可以对sums运行二进制搜索以获取O(log(n))的索引。

learn BST, it's will the fastest algo for your problem: 学习BST,这将是您解决问题的最快方法:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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