初学者Swift 3:如何在数组中查找总计为给定数字的对 [英] Beginner Swift 3: How to find pairs in array that add up to given number

查看:63
本文介绍了初学者Swift 3:如何在数组中查找总计为给定数字的对的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

需要遍历一个数组并说是否有任何数字对加起来为8

Need to loop through an array and say whether there are any pairs of numbers that sum to 8

例如[1,2,4,4] =是

e.g. [1,2,4,4] = yes

可以使它与许多嵌套的if语句一起使用,但是如果数组发生更改,这将是不切实际的.

Can get it working with lots of nested if statements but this will be impractical if the array changes.

如果i +(i.indexPosition +1 {i旁边的数字})== 8,我理想地想对我说,然后输出true,如果不是false,则移至下一个迭代数字设置

What I'd ideally like to do is say for i if i + (i.indexPosition +1 {Number next to i})) == 8 then print true, if not false, then move onto the next iteration of numbersSet

想知道是否有人知道可以在这里使用的更好的逻辑吗?非常感谢!

Wondering if someone knew some better logic that could be used here? Many thanks!!

例如

var numbersSet = [1, 2, 4, 4]

for i in numbersSet2 {

    var targetSum = 8

    if i + numbersSet2[1] == targetSum {

        print("True")
    } else { // Nested if statements here

        print("False")
    }
}

推荐答案

您要检查所有总和numbers[i] + numbers[j]其中 i < j,最简单的方法是像这样的嵌套循环:

You want to check all sums numbers[i] + numbers[j] where i < j, and the easiest way to do so is a nested loop like this:

func checkPairs(in numbers: [Int], forSum target: Int) -> Bool {

    for i in 0..<numbers.count {
        for j in i+1..<numbers.count {
            if numbers[i] + numbers[j] == target {
                return true
            }
        }
    }
    return false
}

可以使用enumerated()方法避免数组查找 和数组切片:

The array lookups can be avoided by using the enumerated() method and array slices:

func checkPairs(in numbers: [Int], forSum target: Int) -> Bool {

    for (i, x) in numbers.enumerated() {
        for y in numbers[i+1 ..< numbers.count] {
            if x + y == target {
                return true
            }
        }
    }
    return false
}

此处x是外循环的当前元素,而i是外循环的当前元素 指数. y是开始的内部循环的当前元素 枚举i + 1.

Here x is the current element of the outer loop and i its index. y is the current element of the inner loop which starts enumerating at i + 1.

示例:

print(checkPairs(in: [1, 2, 4, 4], forSum: 8))
print(checkPairs(in: [1, 2, 4, 4], forSum: 7))

上面的函数 可以更紧凑地编写为

The above function could be written more compactly as

func checkPairs(in numbers: [Int], forSum target: Int) -> Bool {

    return numbers.enumerated().contains(where: { (i, x) -> Bool in
        numbers[i+1 ..< numbers.count].contains(target - x)
    })
}

如果给定数字按不减的顺序排列,则可以 通过终止内循环来提高性能 如果无法达到目标金额:

If the given numbers are in non-decreasing order then you can improve the performance by terminating the inner loop if the target sum cannot be reached:

func checkPairs(in numbers: [Int], forSum target: Int) -> Bool {

    for (i, x) in numbers.enumerated() {
        for y in numbers[i+1 ..< numbers.count] {
            if x + y == target {
                return true
            }
            if x + y > target {
                break
            }
        }
    }
    return false
}

对于不减少的数组,效率更高 解决方案是对target - x进行 binary search 对于每个数组元素x.这是一个可能的二进制搜索 实施( https://stackoverflow.com/a/40226976/1187415 的变体):

For an array of non-decreasing numbers an even more efficient solution would be to do a binary search for target - x for each array element x. Here is a possible binary search implementation (a variant of https://stackoverflow.com/a/40226976/1187415):

extension Collection where Iterator.Element: Comparable {

    func binarySearch(element: Iterator.Element) -> Bool {
        var low = startIndex
        var high = endIndex
        while low != high {
            let mid = index(low, offsetBy: distance(from: low, to: high)/2)
            if self[mid] < element {
                low = index(after: mid)
            } else if element < self[mid] {
                high = mid
            } else {
                return true
            }
        }
        return false
    }
}

然后可以用作

func checkPairs(in numbers: [Int], forSum target: Int) -> Bool {

    return numbers.enumerated().contains(where: { (i, x) -> Bool in
        numbers[i+1 ..< numbers.count].binarySearch(element: target - x)
    })
}

这篇关于初学者Swift 3:如何在数组中查找总计为给定数字的对的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆