使用过多的IF语句是否有问题?迅速

婴儿程序员

我目前正在完成关于黑客级别的挑战,称为“比较三元组(https://www.hackerrank.com/challenges/compare-the-triplets/problem)”,我只是想知道是否使用过多的IF语句被认为是不好的编程方法实践?除了使用switch语句外,还有哪些选择。请在下面查看我的代码解决方案:

import Foundation

func compareTriplets(a: [Int], b: [Int]) -> [Int] {
    
  var compareArray = [0,0]
    
    if a[0] == b[0]{
      compareArray[0] = compareArray[0]
    }
    if a[0] < b[0]{
      compareArray[0] = compareArray[0] + 1
    }
    if a[1] < b[1] {
        compareArray[0] = compareArray[0] + 1
    }
    if a[2] < b[2] {
        compareArray[0] = compareArray[0] + 1
    }
    if a[0] > b[0]{
      compareArray[1] = compareArray[1] + 1
    }
    if a[1] > b[1] {
        compareArray[1] = compareArray[1] + 1
    }
    if a[2] > b[2] {
        compareArray[1] = compareArray[1] + 1
    }
    
    return compareArray
}

print(compareTriplets(a: [17,28,30], b: [99,28,8]))
米克纳什

如果您发送的数组中有越来越多的元素,这将扩展很多。

为什么不尝试类似的东西

func compareTriplets(a: [Int], b: [Int]) -> [Int] {
    var compareArray = [0,0]
    
    if a.count != b.count {
        return compareArray
    }
    for index in 0..<(a.count) {
        if a[index] > b[index] {
            compareArray[0] += 1
        }
        else if a[index] < b[index] {
            compareArray[1] += 1
        }
    }
    
    return compareArray
}

当然,如果数组长度可以不同,那么您可以选择最小或最小数组长度。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章