Find a pair of elements from an array whose sum equals a given number

后端 未结 30 1422
暗喜
暗喜 2020-11-22 10:14

Given array of n integers and given a number X, find all the unique pairs of elements (a,b), whose summation is equal to X.

The following is my solution, it is O(nLo

30条回答
  •  爱一瞬间的悲伤
    2020-11-22 11:01

    Another solution in Swift: the idea is to create an hash that store values of (sum - currentValue) and compare this to the current value of the loop. The complexity is O(n).

    func findPair(list: [Int], _ sum: Int) -> [(Int, Int)]? {
        var hash = Set() //save list of value of sum - item.
        var dictCount = [Int: Int]() //to avoid the case A*2 = sum where we have only one A in the array
        var foundKeys  = Set() //to avoid duplicated pair in the result.
    
        var result = [(Int, Int)]() //this is for the result.
        for item in list {
    
            //keep track of count of each element to avoid problem: [2, 3, 5], 10 -> result = (5,5)
            if (!dictCount.keys.contains(item)) {
                dictCount[item] = 1
            } else {
                dictCount[item] = dictCount[item]! + 1
            }
    
            //if my hash does not contain the (sum - item) value -> insert to hash.
            if !hash.contains(sum-item) {
                hash.insert(sum-item)
            }
    
            //check if current item is the same as another hash value or not, if yes, return the tuple.
            if hash.contains(item) &&
                (dictCount[item] > 1 || sum != item*2) // check if we have item*2 = sum or not.
            {
                if !foundKeys.contains(item) && !foundKeys.contains(sum-item) {
                    foundKeys.insert(item) //add to found items in order to not to add duplicated pair.
                    result.append((item, sum-item))
                }
            }
        }
        return result
    }
    
    //test:
    let a = findPair([2,3,5,4,1,7,6,8,9,5,3,3,3,3,3,3,3,3,3], 14) //will return (8,6) and (9,5)
    

提交回复
热议问题