160. 相交链表 (Swift版本)

题目描述

最简单直接的解法

遍历 headA 的所有节点, 看 headB 中是否有相交的节点

swift 复制代码
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     public var val: Int
 *     public var next: ListNode?
 *     public init(_ val: Int) {
 *         self.val = val
 *         self.next = nil
 *     }
 * }
 */

class Solution {
 
func getIntersectionNode(_ headA: ListNode?, _ headB: ListNode?) -> ListNode? {
    var next: ListNode? = headA
    while next != nil {
        if containNode(headB, next) {
            return next
        }
        next = next?.next
    }
    return nil
}

func containNode(_ headB: ListNode?, _ node: ListNode?) -> Bool {
    var next: ListNode? = headB
    while next != nil {
        if node === next { return true }
        next = next?.next
    }
    return false
}
}

哈希集合优化

因为示例中的 ListNode 没有实现 Hash 相关协议, 所以无法使用 Set, 这里使用 Array 代替. (LeetCode, 咱能不能重视一下 Swift 用户, OK ?)

swift 复制代码
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     public var val: Int
 *     public var next: ListNode?
 *     public init(_ val: Int) {
 *         self.val = val
 *         self.next = nil
 *     }
 * }
 */

class Solution {


var globalSet = Array<ListNode?>()
 
func getIntersectionNode(_ headA: ListNode?, _ headB: ListNode?) -> ListNode? {
    var next: ListNode? = headA

    if (globalSet.contains { $0 === next }) {
        return next
    }

    while next != nil {
        if containNode(headB, next) {
            return next
        }
        next = next?.next
    }
    return nil
}

func containNode(_ headB: ListNode?, _ node: ListNode?) -> Bool {

    var next: ListNode? = headB

    while next != nil {
        if node === next { return true }
        if (!globalSet.contains { $0 === next }) {
            globalSet.append(next)
        }
        next = next?.next
    }
    return false
}

}

上面两个方法提交后, 结果都是: 超出时间限制

双指针

swift 复制代码
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     public var val: Int
 *     public var next: ListNode?
 *     public init(_ val: Int) {
 *         self.val = val
 *         self.next = nil
 *     }
 * }
 */

class Solution {
    func getIntersectionNode(_ headA: ListNode?, _ headB: ListNode?) -> ListNode? {
        if headA == nil || headB == nil {
            return nil
        }
        var pA = headA, pB = headB
        while pA !== pB {
            pA = pA == nil ? headB : pA?.next
            pB = pB == nil ? headA : pB?.next
        }
        return pA
    }
}
相关推荐
白狐_7983 分钟前
408 数据结构算法题 01:线性表暴力求解保分指南
java·数据结构·算法
冻柠檬飞冰走茶16 分钟前
PTA基础编程题目集 7-31 字符串循环左移(C语言实现)
c语言·开发语言·数据结构·算法
Hi李耶29 分钟前
【LeetCode】4-寻找两个正序数组的中位数
算法·leetcode·职场和发展
来一碗刘肉面1 小时前
树的存储结构
数据结构
GrowthDiary0072 小时前
算法题:寻找二维数组top k问题
数据结构·python·算法
SHARK_pssm2 小时前
【数据结构——栈】
数据结构
阿米亚波3 小时前
【C++ STL】std::unordered_multiset
开发语言·数据结构·c++·笔记·stl
-dzk-4 小时前
【链表】LC 160.相交链表
数据结构·链表
Hi李耶4 小时前
【LeetCode】6-Z字形变换
算法·leetcode·职场和发展
AKA__Zas4 小时前
芝士算法(前缀和2.0)
java·数据结构·算法·leetcode·哈希算法·学习方法