-1

Find given numbers of elements from an unsorted array whose sum equals a given number.

I have write the below code, it's almost work. but the complexity is O(n^2). Is there a better solution?

(function test(sum = 14, n = 4, nums = [7, 6, 1, 3, 2, 5, 4]) {

  for (var i = 0; i < nums.length; i++) {
    var rest = sum
    var ret = []
    var j = i;
    do {
      if (rest - nums[j] >= 0) {
      rest = rest - nums[j]
    } else {
      j++
      continue
    }

    ret.push(nums[j])

    if (rest == 0 && ret.length == n) {
      console.log("done", ret)
    }
    j++
 } while (j < nums.length)

}
})()
Anders Lau
  • 3
  • 1
  • 6

1 Answers1

2

You would need a hashtable to maintain a list of numbers you visited or list of all numbers in the given array. So at each iteration, you find the complement (given sum - nums[i]). Since you looking for more than a pair of values, you would need to find keys in the hashtable that add up to such complement. The takeaway here is that hashmap has lookup time of O(1)--assuming no/few collisions--whereas iterating through rest of remaining array would result in O(n^2)

夢のの夢
  • 4,060
  • 5
  • 27
  • 49