Ordering arrays of sorted Int

后端 未结 1 1593
不知归路
不知归路 2021-01-23 03:01

Is there a short & clean way to compare 2 arrays of sorted Int ?

Like [1,4,7] should come before [1,5] but after [1,2,3

相关标签:
1条回答
  • 2021-01-23 03:18

    A possible implementation (explanations inline):

    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
    }
    

    Example:

    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)
    
    0 讨论(0)
提交回复
热议问题