力扣第一题—python&C++
- 两数之和的c++和python的一些解法
C++
遍历
在这部分主要通过i和j分别代表第一个数和第二个数的下标进行遍历,若和与target相等就返回两个下标
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
for (int i = 0; i < nums.size(); i ++) {
for (int j = i+1; j < nums.size(); j++) {
if (nums[i] + nums[j] == target) {
return {i,j};
}
}
}
return {};
}
};
有个问题啊,就是这个代码里数组长度使用nums.size来获取,,我一开始用的
length = sizeof(nums) / sizeof(nums[0]);
来得到数组长度,但是会报错。。。不知道为啥。。有大佬可以指点一下么?
哈希表法
C++中map的用法
map是STL的一个关联容器,它提供一对一的hash。
map(key,value)
key是关键字
value是关键字的值
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
map<int,int> a; //定义图
vector<int> result(2,-1); //结果保存
for (int i=0; i<nums.size(); i++) {
a.insert(map<int,int>::value_type(nums[i],i));
} //数据插入
for (int i=0; i<nums.size(); i++) {
if (a.count(target - nums[i])>0&&a[target - nums[i]] != i) {
//a.count(i) 寻找a中key等于i的个数
result[0] = i;
result[1] = a[target - nums[i]];
break;
}
}
return result;
}
};
改进哈希
看到了一个改进哈希的方法,主要在于不需要将全部数据输入,在输入的同时找匹配的key值。找到返回;找不到将其输入,进行下一轮循环。
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
map<int,int> a; //构建map
vector<int> result(2,-1); //构建结果向量
for (int i = 0; i < nums.size(); i ++) {
if (a.count(target - nums[i]) > 0) {
result[0] = i;
result[1] = a[target - nums[i]];
break;
}
a[nums[i]] = i;
}
return result;
}
};
python
我也在学python,一边学一边写,实战时最好的学习不是么😂
遍历法
nums.index()寻找另一半数值的下标
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
lens = len(nums) #取长度
j = -1 #记录结果
for i in range(lens):
if (target - nums[i]) in nums:
if (nums.count(target - nums[i]) == 1) & ((target - nums[i]) ==nums[i]):
#保证存在的另一半不是i本身
continue
else:
j = nums.index(target - nums[i], i+1)
#从i+1开始找另一半的下标
break
if j > 0:
result = [i, j]
else:
result = []
return result
字典模拟哈希法
字典的每个键值 key=>value 对用冒号 : 分割,每个键值对之间用逗号 , 分割,整个字典包括在花括号 {} 中 ,格式如下所示:
d = {key1 : value1, key2 : value2 }
是不是和哈希表的结构很像
enumerate() 函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标,一般用在 for 循环当中。
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
hashmap = {}
for ind, num in enumerate(nums):
hashmap[num] = ind
for i ,num in enumerate(nums):
j = hashmap.get(target - num)
if j is not None and j != i:
return [i, j]
改进哈希法
思路和c++的改进哈希思想相似
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
hashmap = {}
for ind, num in enumerate(nums):
if hashmap.get(target - num) != None:
return [ind,hashmap.get(target - num)]
hashmap[num] = ind
引用
力扣作者:chenlele 链接:https://leetcode-cn.com/problems/two-sum/solution/liang-shu-zhi-he-by-gpe3dbjds1/
力扣作者:lao-la-rou-yue-jiao-yue-xiang 链接:https://leetcode-cn.com/problems/two-sum/solution/xiao-bai-pythonji-chong-jie-fa-by-lao-la-rou-yue-j/