algorithm-base/animation-simulation/数组篇/leetcode1两数之和.md

127 lines
4.2 KiB
Java
Raw Normal View History

2021-03-20 08:30:29 +00:00
> **[tan45du_one](https://raw.githubusercontent.com/tan45du/tan45du.github.io/master/个人微信.15egrcgqd94w.jpg)** ,备注 github + 题目 + 问题 向我反馈
>
>
>
> <u>[****](https://raw.githubusercontent.com/tan45du/test/master/微信图片_20210320152235.2pthdebvh1c0.png)</u> 两个平台同步,想要和题友一起刷题,互相监督的同学,可以在我的小屋点击<u>[**刷题小队**](https://raw.githubusercontent.com/tan45du/test/master/微信图片_20210320152235.2pthdebvh1c0.png)</u>进入。
2021-03-20 07:48:03 +00:00
#### [1. ](https://leetcode-cn.com/problems/two-sum/)
2021-03-17 11:42:49 +00:00
****
> nums target
>
> 使
**:**
> nums = [2, 7, 11, 15], target = 9
>
> nums[0] + nums[1] = 2 + 7 = 9
> [0, 1]
****
****
L,RLRLL
![](https://cdn.jsdelivr.net/gh/tan45du/github.io.phonto2@master/myphoto/微信图片_20210104150003.3unncifeoe80.jpg)
绿3绿 target - 3 = 2
****
```java
class Solution {
public int[] twoSum(int[] nums, int target) {
if(nums.length < 2){
return new int[0];
}
int[] rearr = new int[2];
//查询元素
for(int i = 0; i < nums.length; i++){
for(int j = i+1; j < nums.length; j++ ){
//发现符合条件情况
if(nums[i] + nums[j] ==target){
rearr[0] = i;
rearr[1] = j;
}
}
}
return rearr;
}
}
```
****
****
target 9 2 79 - 2 =7 7 2 key value
****
![](https://cdn.jsdelivr.net/gh/tan45du/tan45du.github.io.photo@master/photo/两数之和.7228lcxkqpw0.gif)
****
2021-04-26 06:44:47 +00:00
Java Code:
2021-03-17 11:42:49 +00:00
```java
class Solution {
public int[] twoSum(int[] nums, int target) {
HashMap<Integer,Integer> map = new HashMap<Integer,Integer>();
for(int i = 0; i < nums.length; i++){
//如果存在则返回
if(map.containsKey(target-nums[i])){
return new int[]{map.get(target-nums[i]),i};
}
//不存在则存入
map.put(nums[i],i);
}
return new int[0];
}
}
```
2021-04-26 06:44:47 +00:00
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 };
2021-04-26 06:55:44 +00:00
m[nums[i]] = i;
2021-04-26 06:44:47 +00:00
}
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);
}
};
```
2021-03-20 07:48:03 +00:00