Adding elements of two big arrays in java

无人久伴 提交于 2019-12-23 04:58:05

问题


I have to come up with an algorithm that adds elements of two big arrays(size of each array is 10⁹ of integers that can go up to 10⁹). When declaring two arrays in java with size of 10⁹ each, I get a memory exception! The problem statement: http://bit.ly/1XWbUca


回答1:


by analyzing the input constraints you can see that you can get 2*10^5 * 10^9 array accesses in the worst case if you implement the solution using two arrays of ints. So that approach will not do. If you somehow solve your MLE error, you will almost certainly get TLE.

There is another way... there is another option :)

you only have 200k operations, that means, you only have to pay attention to 2*200k points (for each operation you have start and end index). If you keep your operations in the sorted array of pairs , where ind is starting or ending index of operation and value is positive for starting index and negative for ending index.

Answering the query can be done by looping through that array and keeping a sum variable to which you add a value for each ind,value pair you encounter.

While that approach is marginally better, because it can add a value to the segment of an array in O(1) it still requires O(n) for queries in the worst case.

So, I imagine the custom segment tree implementation is the way to solve this one.

I don't know much about it, but you can look it up.

Basically, segment tree will store all your segments in a tree-like data structure, that means the access and deletion of elements/segments takes O(log n) time... which is good. Segments in this case would be the range of particular operation (start index, end index). Each node of the tree would also keep a value that you should add to that segment.

And you would have one segment tree for both arrays.

Since I don't know what I'm talking about, you can check someone who does.



来源:https://stackoverflow.com/questions/32536920/adding-elements-of-two-big-arrays-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!