forked from qiubaiying/qiubaiying.github.io
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Create 2019-03-04-Leetcode01-2019.md
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.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 {}; | ||
} | ||
}; | ||
|
||
|