-
Notifications
You must be signed in to change notification settings - Fork 0
/
160.swift
73 lines (60 loc) · 1.6 KB
/
160.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
/**
* 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? {
// 计算长度,对齐后两两比较
func len(_ head: ListNode?) -> Int {
var n: ListNode? = head
var c = 0
while n != nil {
n = n!.next
c += 1
}
return c
}
let la = len(headA)
let lb = len(headB)
let common = min(la, lb)
var a = headA
var b = headB
for _ in 0..<(la - common) {
a = a!.next
}
for _ in 0..<(lb - common) {
b = b!.next
}
while a != nil {
if a === b {
return a
}
a = a!.next
b = b!.next
}
return nil
}
}
// 一个别人的精妙的解法
// 相当于把A后面补个B,B后面补个A,这样总长度就相等了
class Solution {
func getIntersectionNode(_ headA: ListNode?, _ headB: ListNode?) -> ListNode? {
if headA == nil || headB == nil {
return nil
}
var a: ListNode? = headA
var b: ListNode? = headB
while a !== b {
a = a == nil ? headB : a?.next
b = b == nil ? headA : b?.next
}
return a;
}
}