mirror of
https://github.com/chefyuan/algorithm-base.git
synced 2024-12-27 21:06:17 +00:00
Merge pull request #12 from azl397985856/patch-1
feat(ml): leetcode1两数之和 添加 JS 和 CPP 代码
This commit is contained in:
commit
c4a6b4f5d3
@ -69,6 +69,8 @@ class Solution {
|
||||
|
||||
**题目代码:**
|
||||
|
||||
Java Code:
|
||||
|
||||
```java
|
||||
class Solution {
|
||||
public int[] twoSum(int[] nums, int target) {
|
||||
@ -88,5 +90,37 @@ class Solution {
|
||||
}
|
||||
```
|
||||
|
||||
C++ Code:
|
||||
|
||||
```cpp
|
||||
class Solution {
|
||||
public:
|
||||
vector<int> twoSum(vector<int>& nums, int target) {
|
||||
unordered_map<int, int> m;
|
||||
for (int i = 0; i < nums.size(); ++i) {
|
||||
int t = target - nums[i];
|
||||
if (m.count(t)) return { m[t], i };
|
||||
m[nums[i]] = i;
|
||||
}
|
||||
return {};
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
JS Code:
|
||||
|
||||
```js
|
||||
const twoSum = function (nums, target) {
|
||||
const map = new Map();
|
||||
for (let i = 0; i < nums.length; i++) {
|
||||
const diff = target - nums[i];
|
||||
if (map.has(diff)) {
|
||||
return [map.get(diff), i];
|
||||
}
|
||||
map.set(nums[i], i);
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
|
||||
|
||||
|
Loading…
Reference in New Issue
Block a user