有没有更好的方法来比较两个排序的数组?

Is there a better way to compare two sorted arrays?

在 Swift 中,我有两个数组,已按从大到小的顺序排序,这意味着数组的值是 Comparable。我想定义一种比较两个数组的自定义方法,说一个是 "less than" 另一个。元素较少的数组总是小于较大的数组。我想出的东西工作得很好,但 < 运算符似乎太笨重了。只是感觉应该有某种方法来压缩它,或者有一个内置函数或内置函数的组合可以完成我想要的。这是我拥有的:

func <<T where T: Comparable>(lhs: [T], rhs: [T]) -> Bool {
  if lhs.count < rhs.count {
    return true
  }

  for i in 0..<lhs.count {
    if lhs[i] > rhs[i] {
      return false
    }
  }

  return true
}

let first = [9, 8, 7, 6, 4]
let second = [9, 8, 7, 6, 5]
let third = [8, 7, 6, 5, 4]
let fourth = [9, 8, 7, 6]

let firstSecondComp: Bool = first < second   // true
let secondFirstComp: Bool = second < first   // false
let secondThirdComp: Bool = second < third   // false
let thirdSecondComp: Bool = third < second   // true
let firstThirdComp: Bool = first < third     // false
let thirdFirstComp: Bool = third < first     // true

let fourthFirstComp: Bool = fourth < first   // true
let fourthSecondComp: Bool = fourth < second // true
let fourthThirdComp: Bool = fourth < third   // true

有什么方法可以改进比较函数的主体吗?

编辑

修复 Leo Dabus 指出的崩溃并包括 Martin R 的回答:

func <<T where T: Comparable>(lhs: [T], rhs: [T]) -> Bool {
  if lhs.count < rhs.count {
    return true
  }
  else if lhs.count > rhs.count {
    return false
  }

  return !zip(lhs, rhs).contains { [=11=] >  }
}

你的比较函数可以写成

func <<T where T: Comparable>(lhs: [T], rhs: [T]) -> Bool {

    return lhs.count < rhs.count || !zip(lhs, rhs).contains { [=10=] >  }
}

这里 zip() returns 是来自两者的对的枚举 数组,然后检查是否有一个元素来自第一个 数组大于第二个数组中的对应元素。

这给出了相同的结果是你所有测试用例的函数。

正如@Leo 正确注意到的那样,如果第一个 数组比第二个有更多的元素。对于 zip(), 多余的元素将被忽略。

备注:如果比较应该returnfalse如果第一个数组更长 那么你可以把它写成

return lhs.count <= rhs.count && (lhs.count < rhs.count || !zip(lhs, rhs).contains { [=11=] >  })