两数之和(Python and C++解法)

题目:

给定一个整数数组 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

思路:

  双重循环复杂度较高。可以借助字典结构,当遍历到某一数值num时,去查找(target-num)是否存在于字典中,该查询的时间复杂度是O(1)。

Python题解:

 1 class Solution(object):
 2     @staticmethod  # two_sum方法不涉及对类属性的操作
 3     def two_sum(nums, target):
 4         num_store = dict()  # 存储key-value
 5         for i, num in enumerate(nums):
 6             if target - num in num_store:
 7                 return [i, num_store[target - num]]
 8             else:
 9                 num_store[num] = i  # 此处key是num,value是i,需要使用num定位其下标i
10 
11 if __name__ == '__main__':
12     the_target = 9
13     the_nums = [2, 7, 11, 15]
14     s = Solution()
15     result = s.two_sum(the_nums, the_target)
16     print(result)  # [1, 0]

C++题解:

 1 #include "pch.h"
 2 #include <iostream>
 3 #include <vector>
 4 #include <unordered_map>
 5 using namespace std;
 6 
 7 class Solution {
 8 public:
 9     vector<int> twoSum(vector<int> &nums, int target) {  // vector作为函数的参数或者返回值时需要注意:“&”绝对不能少
10         unordered_map<int, int> hash;  // unordered_map底层是哈希表,查找效率较高
11         vector<int> result;
12         int numsSize = nums.size();
13         for (int i = 0; i < numsSize; i++) {
14             int numToFind = target - nums[i];
15             if (hash.find(numToFind) != hash.end()) {  // 判断一个值是否在哈希表中的方法
16                 result.push_back(i);
17                 result.push_back(hash[numToFind]);
18                 return result;
19             }
20             else
21                 hash[nums[i]] = i;
22         }
23         //return result;  // leetcode上必须有这一行的返回结果
24     }
25 };
26 
27 int main() {
28     int theTarget = 9;
29     vector<int> theNums{2, 7, 11, 15};  // 初始化vector的方法
30     Solution s;
31     for (auto res: s.twoSum(theNums, theTarget)) {  // 打印vector的方法
32         cout << res << " ";  // 1 0
33     }
34 }

 

posted @ 2020-05-29 23:59  孔子?孟子?小柱子!  阅读(255)  评论(0编辑  收藏  举报