【问题标题】:Find the pair in array with condition在有条件的数组中找到对
【发布时间】:2023-03-04 15:37:01
【问题描述】:

假设我有一个 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
}

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

例如:

findPair([1,2,3,4,5], 7) // will return (2, 5), because 2 + 5 = 7

但是这个算法的复杂度是O(n^2)

有没有更快的方法?

【问题讨论】:

标签: arrays swift algorithm


【解决方案1】:

尝试以下方法:

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--;

}

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

【讨论】:

  • 你打字太快了,我在输入相同的解决方案(:
【解决方案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
}

【讨论】:

    【解决方案3】:

    肯定有更快的 O(n log(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 decrement second pointer and go to step 3.*
    

    【讨论】:

    • 排序是O(n * log_2(n)),所以算法作为一个整体必须至少有这个时间复杂度,或者更糟。不能是O(n)
    猜你喜欢
    • 1970-01-01
    • 2023-03-31
    • 2020-05-11
    • 2023-04-09
    • 2021-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-07
    相关资源
    最近更新 更多