在条件中找到数组对

时间:2016-06-01 08:54:34

标签: arrays swift algorithm

假设我有一个Int数组,我想在这个数组中找到一对数字,该对的总和等于一个数字,如下所示:

var array = [{name:'test', lastname: 'test', gender:'f'},{name:'test1', lastname: 'test1', gender:'m'},{name:'test2', lastname: 'test2', gender:'m'}],
    element;

array.some(function (a) {
    if (a.gender === 'm') {
        element = a;
        return true;
    }
});
console.log(element);

第一个参数是Int数组,第二个参数是我们需要比较该数组中某些对的数字。

例如:

func findPair(list: [Int], _ sum: Int) -> (Int, Int)? {
    for i in 0..<list.count - 1{
        for j in (i+1)..<list.count {
            let sumOfPair = list[i] + list[j]
            if sumOfPair == sum {
                return (list[i], list[j])
            }
        }
    }
    return nil
}

但该算法的复杂性为 O(n ^ 2)

有没有更快的方法?

3 个答案:

答案 0 :(得分:3)

尝试以下方法:

sort(arr,arr+n);//Sort the array

low=0;

high=n-1; // The final index number (pointing to the greatest number)

while(low<=high)
{
   if(arr[low]+arr[high]==num)
   {        print(low,high);
            break;
    }
   else if(arr[low]+arr[high]<num)
         low++;
   else if(arr[low]+arr[high]>num)
         high--;

}

基本上,你在这里遵循贪婪的方法......希望它有效.. :)

答案 1 :(得分:2)

解决这个问题肯定要快得多 O(n)。以下是伪算法: -

1) Sort the given array.
2) Take two pointers. One pointing to the beginning and other pointing to the end.
3) Check if sum of two values pointed by two pointer is equal to given number.
4) If yes then return.
5) If greater than increment first pointer and go to step 3.
6) Else increment second pointer and go to step 3.*

答案 2 :(得分:2)

试试这个:

func findPair(list: [Int], _ sum: Int) -> (Int, Int)? {
    //save list of value of sum - item.
    var hash = Set<Int>()
    var dictCount = [Int: Int]()
    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 5+5 = 10 or not.
        {
            return (item, sum-item)
        }
    }
    return nil
}