classSolution: defminOperations(self, nums: List[int]) -> int: if gcd(*nums) > 1: return -1 n = len(nums) cnt1 = sum(x == 1for x in nums) if cnt1: return n - cnt1
min_size = n for i inrange(n): g = 0 for j inrange(i, n): g = gcd(g, nums[j]) if g == 1: # 这里本来是 j-i+1,把 +1 提出来合并到 return 中 min_size = min(min_size, j - i) break return min_size + n - 1
funcminOperations(nums []int)int { n, gcdAll, cnt1 := len(nums), 0, 0 for _, x := range nums { gcdAll = gcd(gcdAll, x) if x == 1 { cnt1++ } } if gcdAll > 1 { return-1 } if cnt1 > 0 { return n - cnt1 }
minSize := n for i := range nums { g := 0 for j, x := range nums[i:] { g = gcd(g, x) if g == 1 { // 这里本来是 j+1,把 +1 提出来合并到 return 中 minSize = min(minSize, j) break } } } return minSize + n - 1 }
funcgcd(a, b int)int { for a != 0 { a, b = b%a, a } return b }
funcmin(a, b int)int { if a > b { return b } return a }
classSolution: defminOperations(self, nums: List[int]) -> int: if gcd(*nums) > 1: return -1 n = len(nums) cnt1 = sum(x == 1for x in nums) if cnt1: return n - cnt1
min_size = n a = [] # [GCD,相同 GCD 闭区间的右端点] for i, x inenumerate(nums): a.append([x, i])
# 原地去重,因为相同的 GCD 都相邻在一起 j = 0 for p in a: p[0] = gcd(p[0], x) if a[j][0] != p[0]: j += 1 a[j] = p else: a[j][1] = p[1] del a[j + 1:]
if a[0][0] == 1: # 这里本来是 i-a[0][1]+1,把 +1 提出来合并到 return 中 min_size = min(min_size, i - a[0][1]) return min_size + n - 1
funcminOperations(nums []int)int { n, gcdAll, cnt1 := len(nums), 0, 0 for _, x := range nums { gcdAll = gcd(gcdAll, x) if x == 1 { cnt1++ } } if gcdAll > 1 { return-1 } if cnt1 > 0 { return n - cnt1 }
minSize := n type result struct{ gcd, i int } a := []result{} for i, x := range nums { for j, r := range a { a[j].gcd = gcd(r.gcd, x) } a = append(a, result{x, i})
// 去重 j := 0 for _, q := range a[1:] { if a[j].gcd != q.gcd { j++ a[j] = q } else { a[j].i = q.i // 相同 gcd 保存最右边的位置 } } a = a[:j+1]