子序列总和

编程入门 行业动态 更新时间:2024-10-14 02:20:12
本文介绍了子序列总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

由于整数数组,例如 [1,2,-3,1] 查找是否有一个子序列,总结为 0 并返回它(例如: [1,2,-3] 或 [2,-3,1] )。 检查每个子序列为O(n ^ 2)这是效率太低。任何想法改善?

Given an array of integers eg [1, 2, -3, 1] find whether there is a sub-sequence that sums to 0 and return it (eg [1, 2, -3] or [2, -3, 1]). Checking every sub-sequence is O(n^2) which is too inefficient. Any idea for improvements?

推荐答案

请一个新的数组,每个元素等于previous元素加一个总和。

Make a new array with each element equal to the sum of the previous elements plus that one.

输入:

1 4 -3 -4 6 -7 8 -5

变成了:

1 5 2 -2 4 -3 5 0 ^ ^

然后寻找匹配所得数组中的元素。

Then look for elements that match in the resulting array.

由于这些重present位置,其中在功能上的整体变化是零,你会发现,如果他们的立场是I和K则子(I + 1,k)是一个零和子序列。 (在这种情况下,[2:6])。

Since these represent locations where the overall change in the function is zero, you will find that if their position is i and k then the subsequence (i+1, k) is a zero-sum subsequence. (In this case, [2:6]).

此外,表中的任意零指示的序列(0,k)是一个零和子序列。对于查找,哈希表或其它快速碰撞定位使得这款O(N)来执行。

Additionally, any zeros in the table indicate that the subsequence (0, k) is a zero-sum subsequence. For the lookup, a hash table or other fast collision locator makes this O(N) to perform.

更多推荐

子序列总和

本文发布于:2023-11-30 00:12:56,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1648071.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:总和   序列

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!