35
35
36
36
<!-- 这里可写通用的实现逻辑 -->
37
37
38
+ ** 方法一:数学**
39
+
40
+ 我们可以发现,每堆力扣币拿完的最少次数,等于该堆力扣币数量除以 $2$ 向上取整的结果之和。
41
+
42
+ 因此,我们只需要遍历每堆力扣币 $x_i$,计算每堆力扣币拿完的最少次数 $\left \lceil x_i/2 \right \rceil$,然后累加即可。
43
+
44
+ 时间复杂度 $O(n)$,其中 $n$ 是数组 $coins$ 的长度。空间复杂度 $O(1)$。
45
+
38
46
<!-- tabs:start -->
39
47
40
48
### ** Python3**
44
52
``` python
45
53
class Solution :
46
54
def minCount (self , coins : List[int ]) -> int :
47
- return sum ((coin + 1 ) // 2 for coin in coins)
55
+ return sum ((x + 1 ) >> 1 for x in coins)
48
56
```
49
57
50
58
### ** Java**
@@ -55,8 +63,8 @@ class Solution:
55
63
class Solution {
56
64
public int minCount (int [] coins ) {
57
65
int ans = 0 ;
58
- for (int coin : coins) {
59
- ans += (coin + 1 ) / 2 ;
66
+ for (int x : coins) {
67
+ ans += (x + 1 ) >> 1 ;
60
68
}
61
69
return ans;
62
70
}
@@ -70,7 +78,9 @@ class Solution {
70
78
public:
71
79
int minCount(vector<int >& coins) {
72
80
int ans = 0;
73
- for (int coin : coins) ans += (coin + 1) / 2;
81
+ for (int x : coins) {
82
+ ans += (x + 1) >> 1;
83
+ }
74
84
return ans;
75
85
}
76
86
};
@@ -79,38 +89,43 @@ public:
79
89
### **Go**
80
90
81
91
```go
82
- func minCount(coins []int) int {
83
- ans := 0
84
- for _, coin := range coins {
85
- ans += (coin + 1) / 2
92
+ func minCount(coins []int) (ans int) {
93
+ for _, x := range coins {
94
+ ans += (x + 1) >> 1
86
95
}
87
- return ans
96
+ return
88
97
}
89
98
```
90
99
91
- ### ** C **
100
+ ### ** TypeScript **
92
101
93
- ``` c
94
- int minCount (int* coins, int coinsSize) {
95
- int res = 0;
96
- for (int i = 0; i < coinsSize; i++) {
97
- int coin = coins[ i] ;
98
- if (coin % 2 == 1) {
99
- res++;
100
- }
101
- res += coin / 2;
102
+ ``` ts
103
+ function minCount(coins : number []): number {
104
+ let ans = 0 ;
105
+ for (const x of coins ) {
106
+ ans += (x + 1 ) >> 1 ;
102
107
}
103
- return res ;
108
+ return ans ;
104
109
}
105
110
```
106
111
107
- ### **TypeScript **
112
+ ### ** Rust **
108
113
109
- ```ts
110
- function minCount(coins: number[]): number {
111
- let ans = 0;
112
- for (const coin of coins) {
113
- ans += Math.floor((coin + 1) / 2);
114
+ ``` rust
115
+ impl Solution {
116
+ pub fn min_count (coins : Vec <i32 >) -> i32 {
117
+ coins . iter (). map (| & x | (x + 1 ) >> 1 ). sum :: <i32 >()
118
+ }
119
+ }
120
+ ```
121
+
122
+ ### ** C**
123
+
124
+ ``` c
125
+ int minCount (int* coins, int coinsSize) {
126
+ int ans = 0;
127
+ for (int i = 0; i < coinsSize; ++i) {
128
+ ans += (coins[ i] + 1) >> 1;
114
129
}
115
130
return ans;
116
131
}
@@ -125,11 +140,11 @@ class Solution {
125
140
* @return Integer
126
141
*/
127
142
function minCount($coins) {
128
- $cnt = 0;
129
- for ($i = 0; $i < count($coins); $i++ ) {
130
- $cnt += floor($coins[$i] / 2) + ($coins[$i] % 2) ;
143
+ $ans = 0;
144
+ foreach ($coins as $x ) {
145
+ $ans += $x + 1 >> 1 ;
131
146
}
132
- return $cnt ;
147
+ return $ans ;
133
148
}
134
149
}
135
150
```
0 commit comments