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
    }
}
相关推荐
FMRbpm26 分钟前
用队列实现栈
数据结构·c++·新手入门
fei_sun32 分钟前
【数据结构】2021年真题
数据结构
立志成为大牛的小牛1 小时前
数据结构——五十九、冒泡排序(王道408)
数据结构·学习·程序人生·考研·算法
papership1 小时前
【入门级-数据结构-3、特殊树:完全二叉树的定义与基本性质】
数据结构·算法
立志成为大牛的小牛1 小时前
数据结构——六十、快速排序(王道408)
数据结构·程序人生·考研·算法·排序算法
量子炒饭大师1 小时前
一天一个计算机知识——【编程百度】向上取整
c语言·数据结构·c++·git·github
子一!!1 小时前
数据结构==B-树==
数据结构·b树
gf13211111 小时前
python_字幕文本、音频、视频一键组合
python·音视频·swift
Dream it possible!1 小时前
LeetCode 面试经典 150_字典树_添加与搜索单词 - 数据结构设计(96_211_C++_中等)
c++·leetcode·面试·字典树