哈希表+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);
}
}

京公网安备 11010502036488号