文章目录
题目描述
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
给出一个整型数组,返回两个数的索引,这两个数加起来等于某个特殊的数
You may assume that each input would have exactly one solution, and you may not use the same element twice.
可以假设每一个输入的数在列表里面都可以找到两个数的和,不可以使用同一个数两次
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
一、BruteForce暴力实现
一些自我的遐想
-
单纯的将他想复杂了,以为只有非负整数,并且应该尽量减少时间,减少遍历和比较的次数
-
思路:
- 保留原来的列表不变,然后生成新的列表,并且将target添加进去,排序
- 在只有正数的情况下,target一定是前面某两个数的和,跟比target大的数没有关系
- 对target前半部分的数进行考虑,分两层遍历
- 特殊情况
- 两个相同的数相加4 = 2 + 2 ,要能分辨出两个2对应的不同的索引
- 0+ 0 = 0,target是零,原数组有两个0,然后返回的索引就是第一个0的索引,要将遍历比较的边界调整到最后一个0
def twoSum2(self,nums,target):
res = list()
nums1 = list(nums)
nums1.append(target)
nums1.sort()
indexOfTarget = [index for index,value in enumerate(nums1) if value == target]
i = indexOfTarget[-1]
for m in range(0,i):
for n in range(i-1,m,-1):
if nums1[m] + nums1[n] == target:
if nums1[m] == nums1[n]:
res = [index for index,value in enumerate(nums) if value == nums1[m]]
else:
res.append(nums.index(nums1[m]))
res.append(nums.index(nums1[n]))
return res
当我看到[-3,0,2,8]时,我就笑了,发现自己太能够臆想了,根本没有说明一定是正整数,然后
python实现BruteForce
def twoSume(self,nums,target):
res = list()
for i in range(0,len(nums)):
for j in range(i+1,len(nums)):
if nums[i] + nums[j] == target:
res.append(i)
res.append(j)
return res
分析总结
- 每天花太多的时间做算法了,关键是不能浪费时间,要审清题目,要按照学习路线继续学习下去了,不能够等待了!
- 注意引用传递,不是说同一个数组用别的变量名替代就可以生成了新的数组,指向的是同一个数组,要想生成新的相同的数组,必须将原数组作为参数传递进构造器,才能生成新的
- print(list.sort())是不可以的,sort()是有返回值的,并不会直接输出排序过的数组
- append()一次也只能添加一个元素,不能写两个
C语言实现——Brute Force(这个内存申请忘记的有点多)
int* twoSum(int* nums, int numsSize, int target, int* returnSize){
for(int i = 0;i < numsSize;i ++)
{
for(int j = i + 1;j < numsSize;j ++)
{
if(nums[i] + nums[j] == target)
{
int* result = (int*)malloc(sizeof(int)*2);
result[0] = i;
result[1] = j;
*returnSize = 2;
return result;
}
}
}
*returnSize = 0;
return NULL;
}
分析与总结
-
*returnSize,是指向函数之外的变量,该变量表示返回的数组的长度,如果有构成target的数字,那返回值就是2,如果没有构成target的数字,返回值就是0.不是用来指向承载结果的数组的,否则会反复出现如下的错误
* 堆栈溢出,将一个指向整型数字的指针指向一个数组
-
申请的内存空间要判定是否申请成功,特别的如果是字符串的情况下,需要将所有的空间进行初始化,都初始化为0,可以效仿如下的操作
二、Hash表实现
介绍
- 通过关键码值映射到表中的一个位置来访问记录,以加快查找的速度。
- 将列表中的所有的数字都映射到hash表中,x+y = target,直接根据x查找y,不用循环比较所有的数字。可以采用边往hash表中追加,边比较判定的方法。如果存在y,其与x相加未target,则通过x可找到y,同样的通过y可以找到x。
python实现
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
adict = dict()
for index,value in enumerate(nums):
temp = target - value
if temp in adict:
return [index,adict.get(temp)]
else:
adict[value] = index
return []