题解 | #牛牛的冒险旅程#
牛牛的冒险旅程
https://www.nowcoder.com/practice/79f7bf3d985c4b33af6d048ab53848d6
哈希表+gcd
import java.util.*;
public class Solution {
public int gcdInCycle (ListNode head) {
// write code here
Set<Integer> set = new HashSet<>();
int g = 0;
while (head != null) {
if (set.contains(head.val)) g = gcd(g, head.val);
set.add(head.val);
head = head.next;
}
return g == 0 ? -1 : g;
}
int gcd(int a, int b) {
return a % b == 0 ? b : gcd(b, a % b);
}
}

