How to write an algorithm to check if the sum of any two numbers in an array/list matches a given number?

前端 未结 14 1968
萌比男神i
萌比男神i 2021-01-30 11:29

How can I write an algorithm to check if the sum of any two numbers in an array/list matches a given number with a complexity of nlogn?

14条回答
  •  执念已碎
    2021-01-30 12:16

    Here is an algorithm that runs in O(n) if array is already sorted or O(n log n) if it isn't already sorted. Takes cues from lot of other answers here. Code is in Java, but here is a pseudo code as well derived from lot of existing answers, but optimized for duplicates generally

    1. Lucky guess if first and last elements are equal to target
    2. Create a Map with current value and its occurrences
    3. Create a visited Set which contains items we already saw, this optimizes for duplicates such that say with an input of (1,1,1,1,1,1,2) and target 4, we only ever compute for 0 and last element and not all the 1's in the array.
    4. Use these variables to compute existence of target in the array; set the currentValue to array[ith]; set newTarget to target - currentValue; set expectedCount to 2 if currentValue equals newTarget or 1 otherwise

      AND return true only if a. we never saw this integer before AND b. we have some value for the newTarget in the map we created c. and the count for the newTarget is equal or greater than the expectedCount

    OTHERWISE repeat step 4 till we reach end of array and return false OTHERWISE;

    Like I mentioned the best possible use for a visited store is when we have duplicates, it would never help if none of elements are duplicates.

    Java Code at https://gist.github.com/eded5dbcee737390acb4

提交回复
热议问题