1. The sum of two numbers
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
解法一:(C++穷举)
Assuming that there is only one answer, to find qualified numerical subscript use brute-force method
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> v(2);//定义了2个整数类型的向量,尖括号里是元素的类型,这里没有初值;
for(int i = 0; i < nums.size(); ++i)//第一个符合两数之和要求的下标;
{
for(int j = i + 1; j < nums.size(); ++j)//第二个下标;
{
if(nums.at(i) + nums.at(j) == target)
{
v.at(0) = i;
v.at(1) = j;
return v;
}
}
}
return v;
}
vector 是向量类型,它可以容纳许多类型的数据,所以称其为容器,头文件是:#include<vector>
nums.size() //返回nums中元素的个数;
v.at()和v[]的作用类似,但是使用at可以检查是否超出范围,比[]更加安全
Python:
#首先将数组进行排序,设置两个指针,分别从头、尾进行查找nums[i]+nums[j]=target的i和j
def solution(nums,target):
nums = sorted(nums) #sorted()函数的作用是对nums进行排序;
i,j = 0,len(nums)-1
while i < j: # 没有这个限制,整个程序就会无限操作下去
if nums[i]+nums[j] == target:
return [i,j]
elif nums[i]+nums[j] > target:
j = j-1 # 因为从小到大已经排好序了,所以和太大的话就找小一位的
elif nums[i]+nums[j] < target:
i = i+1
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
record = {} # 建立一个空字典
for i in range(len(nums)): # 遍历数组
temp = target - nums[i]
if temp in record: # 如果满足条件,则说明
return [record.get(temp),i]
else:
record[nums[i]] = i #在字典中增加一个nums[i]对应i的记录
Python建立字典的方法:
1.用{}建立字典
例如:x={} #创建了一个空字典;
x={“a”:“2”}
2.使用内置函数dict()
*参数类似 a="1"的键值对 字典的key只能是字符串,并且不能加引号 # x=dict(a="1",b="2")
*参数是一个元组,元组内部是一系列包含两个值的元组,例如(("a", "1"), ("b", "2")) # x = dict((("a", "1"), ("b", "2")))
*参数是一个元组,元组内部是一系列包含两个值的列表,例如(["a", "1"], ["b", "2"]) # x = dict((["a", "1"], ["b", "2"]))
*参数是一个列表,列表内部是一系列包含两个值的元组,例如[("a", "1"),("b", "2")] # x = dict([("a", "1"),("b", "2")])
*参数是一个列表,列表内部是一系列包含两个值的列表,例如[["a", "1"],["b", "2"]] # x = dict([["a", "1"],["b", "2"]])
*用户fromkeys创建字典 # dict.fromkeys(("a", "b"), 1) 第一个参数是一个列表或者元组,里边的值为key,第二个参数是所有key的value值
获得字典中键值对的value的值:record.get(key)