@@ -55,13 +55,11 @@ nums 中最大的数是 3
55
55
56
56
<!-- 这里可写通用的实现逻辑 -->
57
57
58
- 最大公约数算法:
58
+ ** 方法一:模拟 **
59
59
60
- ``` java
61
- int gcd(int a, int b) {
62
- return b > 0 ? gcd(b, a % b) : a;
63
- }
64
- ```
60
+ 根据题意模拟即可,即先找出数组 ` nums ` 中的最大值和最小值,然后求最大值和最小值的最大公约数。
61
+
62
+ 时间复杂度 $O(n)$,空间复杂度 $O(1)$。其中 $n$ 为数组 ` nums ` 的长度。
65
63
66
64
<!-- tabs:start -->
67
65
@@ -83,15 +81,15 @@ class Solution:
83
81
class Solution {
84
82
public int findGCD (int [] nums ) {
85
83
int a = 1 , b = 1000 ;
86
- for (int num : nums) {
87
- a = Math . max(a, num );
88
- b = Math . min(b, num );
84
+ for (int x : nums) {
85
+ a = Math . max(a, x );
86
+ b = Math . min(b, x );
89
87
}
90
88
return gcd(a, b);
91
89
}
92
90
93
91
private int gcd (int a , int b ) {
94
- return b > 0 ? gcd(b, a % b) : a ;
92
+ return b == 0 ? a : gcd(b, a % b);
95
93
}
96
94
}
97
95
```
@@ -102,11 +100,8 @@ class Solution {
102
100
class Solution {
103
101
public:
104
102
int findGCD(vector<int >& nums) {
105
- int a = 0, b = 1000;
106
- for (int num : nums) {
107
- a = max(a, num);
108
- b = min(b, num);
109
- }
103
+ int a = * max_element(nums.begin(), nums.end());
104
+ int b = * min_element(nums.begin(), nums.end());
110
105
return gcd(a, b);
111
106
}
112
107
};
@@ -116,33 +111,44 @@ public:
116
111
117
112
```go
118
113
func findGCD(nums []int) int {
119
- a, b := 0, 1000
120
- for _, num := range nums {
121
- a = max(a, num)
122
- b = min(b, num)
114
+ a, b := 1, 1000
115
+ for _, x := range nums {
116
+ if a < x {
117
+ a = x
118
+ }
119
+ if b > x {
120
+ b = x
121
+ }
123
122
}
124
123
return gcd(a, b)
125
124
}
126
125
127
126
func gcd(a, b int) int {
128
- if b > 0 {
129
- return gcd(b, a%b)
127
+ if b == 0 {
128
+ return a
130
129
}
131
- return a
130
+ return gcd(b, a%b)
132
131
}
132
+ ```
133
133
134
- func max(a, b int) int {
135
- if a > b {
136
- return a
137
- }
138
- return b
134
+ ### ** TypeScript**
135
+
136
+ ``` ts
137
+ function findGCD(nums : number []): number {
138
+ let a = 1 ;
139
+ let b = 1000 ;
140
+ for (const x of nums ) {
141
+ a = Math .max (a , x );
142
+ b = Math .min (b , x );
143
+ }
144
+ return gcd (a , b );
139
145
}
140
146
141
- func min(a , b int) int {
142
- if a < b {
143
- return a
144
- }
145
- return b
147
+ function gcd( a : number , b : number ) : number {
148
+ if ( b == 0 ) {
149
+ return a ;
150
+ }
151
+ return gcd ( b , a % b );
146
152
}
147
153
```
148
154
0 commit comments