Wyt00 2020-05-30
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。
示例:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/two-sum
class Sloution(object):
@staticmethod # two_sum方法不涉及对类属性的操作
def two_sum(nums, target):
num_store = dict() # 存储key-value
for i, num in enumerate(nums):
if target - num in num_store:
return [i, num_store[target - num]]
else:
num_store[num] = i # 此处key是num,value是i,需要使用num定位其下标i
if __name__ == ‘__main__‘:
the_target = 9
the_nums = [2, 7, 11, 15]
s = Sloution()
result = s.two_sum(the_nums, the_target)
print(result) # [1, 0]#include "pch.h"
#include <iostream>
#include <vector>
#include <unordered_map>
using namespace std;
class Sloution {
public:
vector<int> twoSum(vector<int> &nums, int target) { // vector作为函数的参数或者返回值时需要注意:“&”绝对不能少
unordered_map<int, int> hash; // unordered_map底层是哈希表,查找效率较高
vector<int> result;
int numsSize = nums.size();
for (int i = 0; i < numsSize; i++) {
int numToFind = target - nums[i];
if (hash.find(numToFind) != hash.end()) { // 判断一个值是否在哈希表中的方法
result.push_back(i);
result.push_back(hash[numToFind]);
return result;
}
else
hash[nums[i]] = i;
}
//return result; // leetcode上必须有这一行的返回结果
}
};
int main() {
int theTarget = 9;
vector<int> theNums{2, 7, 11, 15}; // 初始化vector的方法
Sloution s;
for (auto res: s.twoSum(theNums, theTarget)) { // 打印vector的方法
cout << res << " "; // 1 0
}
}