是否有短片&干净的方式比较2个排序Int
数组?
[1,4,7]
应该在[1,5]
之前,但在[1,2,3,8]
之后
嵌套的for循环可以做到,但我发现它很麻烦。
答案 0 :(得分:4)
可能的实施(内联说明):
func < <T where T: Comparable>(lhs: [T], rhs: [T]) -> Bool {
// Compare all elements up to common length, return
// if a difference is found:
for (l, r) in zip(lhs, rhs) {
if l < r { return true }
if l > r { return false }
}
// All common elements are equal, check if rhs is "longer":
return lhs.count < rhs.count
}
示例:
print([1,4,7] < [1,5]) // true
print([1,4,7] < [1,2,3,8]) // false
print([1,4,7] < [1,4,7,8]) // true (left array is shorter)
print([1,4,7] < [1,4,7]) // false (arrays are equal)