Count unique values in subarrays

坚强是说给别人听的谎言 提交于 2019-12-25 09:49:38

问题


Array a*b is given, which contains numbers up to 1e5, and we have to sum the count of unique numbers in every k*k subarray, there are a-k*b-k subarrays e.g

1 2 3 4 
3 2 4 1

for k=2 subarrays are

{1,2,3,2}(3distinct values)
{2,3,2,4}(3distinct values)
{3,4,4,1}(3distinct values)

output is 9

Is there a faster approach than using a table which stores count of every number ocurrencies in an actaully processed k*k subarray(e.g at index 3 we store count of 3's in a subarray), moving a k*k window by 1 and adding values from right and removing from left, if after incremention value is 1 - increment unique numbers counter; if after decrementation value is 0 - decrement unique numbers counter. After getting to the end of the row, go 1 down and move in the opposite direction. Not worried about memory usage,im just looking for a way to do this faster


回答1:


a == b is an equivalence relation. Given A the set of elements (your subarray), you can find the equivalence classes of the relation with the method you found:

For each element x in the subarray A you take c[x] which is an int (c array elements all initialized to 0). If this c[x] == 0 then you have a new unique element so c[x]++. Otherwise you increment c[x].

This algorithm is linear to the number of elements in the subarray (obviously you iterate this process for each subarray and sum the results to get what you want).

But time complexity can’t be lower, cause you need to check each element anyway.



来源:https://stackoverflow.com/questions/46852306/count-unique-values-in-subarrays

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