Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- struct NSRange {
- location : Int;
- length : Int;
- }
- typealias NSNotFound = Int.max
- //**证明相交最简单的办法就是 -> 证明不是不相交**
- func intersection(_ r1 : NSRange, _ r2 : NSRange) -> NSRange{
- guard r1.location != NSNotFound && r1.length != NSNotFound
- && r2.location != NSNotFound && r2.length != NSNotFound else{
- return NSRange(location: NSNotFound, length: NSNotFound)
- }
- //check if intersection
- if r1.location + r1.length - 1 < r2.location || r2.location + r2.length - 1 < r1.location {
- return NSRange(location: NSNotFound, length: NSNotFound)
- }
- //get intersection
- let startIndex = max(r1.location, r2.location)
- let endIndex = min(r1.location + r1.length - 1, r2.location + r2.length - 1)
- return NSRange(location: startIndex, length: endIndex - startIndex + 1)
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement