简体   繁体   中英

Finding sum of a sorted array in O(log n) Time Complexity

There is a Sorted Array A[1,..,n] where each element in the array is between [0-9] and numbers can be repeated with conditions ie A[i] <= A[i+1] (less than equal to)

Is there any way to compute this in O(log n) time complexity?

Use binary search to find the first occurrence of 0, then the first occurrence of 1, and so on all the way up to 9. That way, you'll know the exact count of 0's, 1's, 2's.. etc in the array.

Array sum = (1's count*1) + (2's count * 2) ... (9's count * 9) .

Total complexity = O(logN) for running binary search 9 times.

Based on the recommended answer, How can you get to know the count of each element in the array? My understanding is, the binary search will give you the first occurrence of that element, but you still need to know the elements greater or lesser than that to count the occurrence and in doing so you will still traverse the whole array, resulting in O(N). Correct me if I am wrong.

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