File tree 3 files changed +76
-0
lines changed
solution/1600-1699/1658.Minimum Operations to Reduce X to Zero
3 files changed +76
-0
lines changed Original file line number Diff line number Diff line change @@ -106,6 +106,33 @@ class Solution {
106
106
}
107
107
```
108
108
109
+ ### ** TypeScript**
110
+
111
+ ``` ts
112
+ function minOperations(nums : number [], x : number ): number {
113
+ const total = nums .reduce ((a , c ) => a + c , 0 );
114
+ if (total < x ) return - 1 ;
115
+ // 前缀和 + 哈希表, 求何为total - x的最长子序列
116
+ const n = nums .length ;
117
+ const target = total - x ;
118
+ let hashMap = new Map ();
119
+ hashMap .set (0 , - 1 );
120
+ let pre = 0 ;
121
+ let ans = - 1 ;
122
+ for (let right = 0 ; right < n ; right ++ ) {
123
+ pre += nums [right ];
124
+ if (! hashMap .has (pre )) {
125
+ hashMap .set (pre , right );
126
+ }
127
+ if (hashMap .has (pre - target )) {
128
+ let left = hashMap .get (pre - target );
129
+ ans = Math .max (right - left , ans )
130
+ }
131
+ }
132
+ return ans == - 1 ? - 1 : n - ans ;
133
+ };
134
+ ```
135
+
109
136
### ** C++**
110
137
111
138
``` cpp
Original file line number Diff line number Diff line change @@ -92,6 +92,33 @@ class Solution {
92
92
}
93
93
```
94
94
95
+ ### ** TypeScript**
96
+
97
+ ``` ts
98
+ function minOperations(nums : number [], x : number ): number {
99
+ const total = nums .reduce ((a , c ) => a + c , 0 );
100
+ if (total < x ) return - 1 ;
101
+ // 前缀和 + 哈希表, 求何为total - x的最长子序列
102
+ const n = nums .length ;
103
+ const target = total - x ;
104
+ let hashMap = new Map ();
105
+ hashMap .set (0 , - 1 );
106
+ let pre = 0 ;
107
+ let ans = - 1 ;
108
+ for (let right = 0 ; right < n ; right ++ ) {
109
+ pre += nums [right ];
110
+ if (! hashMap .has (pre )) {
111
+ hashMap .set (pre , right );
112
+ }
113
+ if (hashMap .has (pre - target )) {
114
+ let left = hashMap .get (pre - target );
115
+ ans = Math .max (right - left , ans )
116
+ }
117
+ }
118
+ return ans == - 1 ? - 1 : n - ans ;
119
+ };
120
+ ```
121
+
95
122
### ** C++**
96
123
97
124
``` cpp
Original file line number Diff line number Diff line change
1
+ function minOperations ( nums : number [ ] , x : number ) : number {
2
+ const total = nums . reduce ( ( a , c ) => a + c , 0 ) ;
3
+ if ( total < x ) return - 1 ;
4
+ // 前缀和 + 哈希表, 求何为total - x的最长子序列
5
+ const n = nums . length ;
6
+ const target = total - x ;
7
+ let hashMap = new Map ( ) ;
8
+ hashMap . set ( 0 , - 1 ) ;
9
+ let pre = 0 ;
10
+ let ans = - 1 ;
11
+ for ( let right = 0 ; right < n ; right ++ ) {
12
+ pre += nums [ right ] ;
13
+ if ( ! hashMap . has ( pre ) ) {
14
+ hashMap . set ( pre , right ) ;
15
+ }
16
+ if ( hashMap . has ( pre - target ) ) {
17
+ let left = hashMap . get ( pre - target ) ;
18
+ ans = Math . max ( right - left , ans )
19
+ }
20
+ }
21
+ return ans == - 1 ? - 1 : n - ans ;
22
+ } ;
You can’t perform that action at this time.
0 commit comments