60
60
61
61
<!-- 这里可写通用的实现逻辑 -->
62
62
63
+ ** 方法一:贪心 + 数学**
64
+
65
+ 对于数组中的每个元素,如果它与前面的元素的最大公约数为 $1$,那么它需要作为一个新的子数组的第一个元素。否则,它可以与前面的元素放在同一个子数组中。
66
+
67
+ 因此,我们先初始化一个变量 $g$,表示当前子数组的最大公约数。初始时 $g=0$,答案变量 $ans=1$。
68
+
69
+ 接下来,我们从前往后遍历数组,维护当前子数组的最大公约数 $g$。如果当前元素 $x$ 与 $g$ 的最大公约数为 $1$,那么我们需要将当前元素作为一个新的子数组的第一个元素,因此,答案加 $1$,并将 $g$ 更新为 $x$。否则,当前元素可以与前面的元素放在同一个子数组中。继续遍历数组,直到遍历结束。
70
+
71
+ 时间复杂度 $O(n \times \log m)$,空间复杂度 $O(1)$。其中 $n$ 和 $m$ 分别是数组的长度和数组中元素的最大值。
72
+
63
73
<!-- tabs:start -->
64
74
65
75
### ** Python3**
69
79
``` python
70
80
class Solution :
71
81
def minimumSplits (self , nums : List[int ]) -> int :
72
- ans, x = 1 , nums[0 ]
73
- for v in nums:
74
- x = gcd(x, v)
75
- if x == 1 :
76
- x = v
82
+ ans, g = 1 , 0
83
+ for x in nums:
84
+ g = gcd(g, x)
85
+ if g == 1 :
77
86
ans += 1
87
+ g = x
78
88
return ans
79
89
```
80
90
@@ -85,12 +95,12 @@ class Solution:
85
95
``` java
86
96
class Solution {
87
97
public int minimumSplits (int [] nums ) {
88
- int ans = 1 , x = nums[0 ];
89
- for (int v : nums) {
90
- x = gcd(x, v);
91
- if (x == 1 ) {
92
- x = v;
98
+ int ans = 1 , g = 0 ;
99
+ for (int x : nums) {
100
+ g = gcd(g, x);
101
+ if (g == 1 ) {
93
102
++ ans;
103
+ g = x;
94
104
}
95
105
}
96
106
return ans;
@@ -108,12 +118,12 @@ class Solution {
108
118
class Solution {
109
119
public:
110
120
int minimumSplits(vector<int >& nums) {
111
- int ans = 1, x = nums[ 0] ;
112
- for (int v : nums) {
113
- x = gcd(x, v);
114
- if (x == 1) {
115
- x = v;
121
+ int ans = 1, g = 0;
122
+ for (int x : nums) {
123
+ g = gcd(g, x);
124
+ if (g == 1) {
116
125
++ans;
126
+ g = x;
117
127
}
118
128
}
119
129
return ans;
@@ -125,12 +135,12 @@ public:
125
135
126
136
```go
127
137
func minimumSplits(nums []int) int {
128
- ans, x := 1, nums[0]
129
- for _, v := range nums {
130
- x = gcd(x, v)
131
- if x == 1 {
132
- x = v
138
+ ans, g := 1, 0
139
+ for _, x := range nums {
140
+ g = gcd(g, x)
141
+ if g == 1 {
133
142
ans++
143
+ g = x
134
144
}
135
145
}
136
146
return ans
@@ -147,7 +157,22 @@ func gcd(a, b int) int {
147
157
### ** TypeScript**
148
158
149
159
``` ts
160
+ function minimumSplits(nums : number []): number {
161
+ let ans = 1 ;
162
+ let g = 0 ;
163
+ for (const x of nums ) {
164
+ g = gcd (g , x );
165
+ if (g == 1 ) {
166
+ ++ ans ;
167
+ g = x ;
168
+ }
169
+ }
170
+ return ans ;
171
+ }
150
172
173
+ function gcd(a : number , b : number ): number {
174
+ return b ? gcd (b , a % b ) : a ;
175
+ }
151
176
```
152
177
153
178
### ** ...**
0 commit comments