Skip to content

Commit

Permalink
Create 2019-03-04-Leetcode01-2019.md
Browse files Browse the repository at this point in the history
leetcode 01
  • Loading branch information
DESKTOP-VL15K8M\ever_lp committed Mar 5, 2019
1 parent c737380 commit acbadbe
Showing 1 changed file with 62 additions and 0 deletions.
62 changes: 62 additions & 0 deletions _posts/2019-03-04-Leetcode01-2019.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
# Leetcode 01 两数之和

## 题目描述
给定一个整数数组nums和一个目标值target,请你再该数组中找出和为目标值的那两个整数,并返回他们的数组的下标。
你可以 假设每种输入只会对应一个答案。但是你不能重复利用这个数组中同样的元素。

## 示例:
给定 nums = [2, 7, 11, 15], target = 9

因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]

## 方法一:
---

暴力解法:

```
`class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
//两个for 循环
int length = nums.size();
for (int i = 0; i < length; i++) {
for (int j = i + 1; j < length; j++) {
if ((nums[i] + nums[j]) == target) {
return {i, j};
}
}
}
return {};
}
};
## 方法二:
---
思路:用hash表来玩,value来存每个元素的index,
扫描hash表,减去target,查下剩下的是否再hash表里面
```
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int, int> indies;
for (int i = 0; i < nums.size(); i++) {
indies[nums[i]] = i;
}

for (int i = 0; i < nums.size(); i++) {
int left = target - nums[i];
//存在,且一个数字只能用一次
if (indies.count(left) && indies[left] != i) {
return {i, indies[left]};
}
}
return {};
}
};


0 comments on commit acbadbe

Please sign in to comment.