Skip to content

Commit 89f4da8

Browse files
committed
feat: add typescript solution to lc problem: No.1658
No.1658.Minimum Operations to Reduce X to Zero
1 parent d4d498f commit 89f4da8

File tree

3 files changed

+76
-0
lines changed

3 files changed

+76
-0
lines changed

solution/1600-1699/1658.Minimum Operations to Reduce X to Zero/README.md

+27
Original file line numberDiff line numberDiff line change
@@ -106,6 +106,33 @@ class Solution {
106106
}
107107
```
108108

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+
109136
### **C++**
110137

111138
```cpp

solution/1600-1699/1658.Minimum Operations to Reduce X to Zero/README_EN.md

+27
Original file line numberDiff line numberDiff line change
@@ -92,6 +92,33 @@ class Solution {
9292
}
9393
```
9494

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+
95122
### **C++**
96123

97124
```cpp
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
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+
};

0 commit comments

Comments
 (0)