find pair of numbers in array that add to given sum

前端 未结 19 2181
萌比男神i
萌比男神i 2020-11-30 20:17

Question: Given an unsorted array of positive integers, is it possible to find a pair of integers from that array that sum up to a given sum?

Constraints: This shou

19条回答
  •  情话喂你
    2020-11-30 20:31

    1. Use count sort to sort the array O(n).
    2. take two pointers one starts from 0th index of array, and another from end of array say (n-1).

      run the loop until low <= high

      Sum = arr[low] + arr[high]  
      if(sum == target)
             print low, high
      if(sum < target)
             low++
      if(sum > target)
             high--
      

      Step 2 to 10 takes O(n) time, and counting sort takes O(n). So total time complexity will be O(n).

提交回复
热议问题