给定一个整数数组
nums
和一个整数目标值target
,
请你在该数组中找出 和为目标值target
的那 两个 整数,
并返回它们的数组下标。
你可以假设每种输入只会对应一个答案。
但是,数组中同一个元素在答案里不能重复出现。
时间复杂度:O(n2)
空间复杂度:O(1)
枚举数组中的每一个数
x
,寻找数组中是否存在target - x
。
当我们使用遍历整个数组的方式寻找
target - x
时,需要注意到每一个位于x
之前的元素都已经和x
匹配过,因此不需要再进行匹配。
而每一个元素不能被使用两次,所以我们只需要在x
后面的元素中寻找target - x
。
// 整数数组:nums,整数数组大小:numsSize,整数目标值:target,返回答案数组大小:returnSize
int* twoSum(int* nums, int numsSize, int target, int* returnSize) {for (int i = 0; i < numsSize; ++i) { // i 遍历 nums 寻找 xfor (int j = i + 1; j < numsSize; ++j) { // j 遍历数组寻找 target - xif (nums[i] + nums[j] == target) { // 找到 x,target - x// 为答案数组开辟两个空间int* ret = malloc(sizeof(int) * 2);// 答案数组分别存放 x 的下标和 target - x 的下标ret[0] = i, ret[1] = j;*returnSize = 2; // 答案数组大小为 2return ret; // 返回答案数组}}}// 没有找到 x 和 target - x 的情况*returnSize = 0; // 答案数组大小置 0return NULL; // 返回 NULL
}
class Solution {
public:// 整数数组:nums,整数目标值:targetvector twoSum(vector& nums, int target) {int n = nums.size(); // 整数数组大小for (int i = 0; i < n; ++i) { // i 遍历 nums 寻找 xfor (int j = i + 1; j < n; ++j) { // j 遍历 nums 寻找 target - xif (nums[i] + nums[j] == target) { // 找到 x,target - xreturn {i, j}; // 返回 x,target - x 下标}}}return {}; // 未找到,返回空值}
};
class Solution:# 函数格式解释,Python3可以对函数参数和返回值进行类型指定和类型检查# nums: List[int],指定整数数组 nums,类型为 int 型 List# target: int,指定整数目标值 target,类型为 int# -> List[int],指定函数返回值类型为 int 型 Listdef twoSum(self, nums: List[int], target: int) -> List[int]:n = len(nums) # 整数数组大小for i in range(n): # i 遍历 nums 寻找 xfor j in range(i + 1, n): # j 遍历 nums 寻找 target - xif nums[i] + nums[j] == target: # 找到 x,target - xreturn [i, j] # 返回 x,target - x 数组下标return [] # 未找到,返回空值
class Solution {public int[] twoSum(int[] nums, int target) {int n = nums.length;for (int i = 0; i < n; ++i) {for (int j = i + 1; j < n; ++j) {if (nums[i] + nums[j] == target) {return new int[]{i, j};}}}return new int[0];}
}
func twoSum(nums []int, target int) []int {for i, x := range nums {for j := i + 1; j < len(nums); j++ {if x+nums[j] == target {return []int{i, j}}}}return nil
}
时间复杂度:O(n)
空间复杂度:O(1)
暴力枚举 时间复杂度较高的原因是寻找
target - x
的时间复杂度过高。
使用哈希表,可以将寻找
target - x
的时间复杂度降低到从O(n)
降到O(1)
。
这样我们创建一个哈希表,对于每一个
x
,我们首先查询哈希表中是否存在target - x
,然后将x
插入到哈希表中,即可保证不会让x
和自己匹配。
// 定义哈希表结构体
struct hashTable {int key; // 值int val; // 值对应在数组中的下标// 此步骤不可省略,变量可以不进行初始化,用于声明此结构体为哈希表UT_hash_handle hh;
};struct hashTable* hashtable; // 定义哈希指针,指向前面的 hashTable 数据结构// 查找 hashtable 中是否已经存在 key
struct hashTable* find(int ikey) { // 通过 key 值来查找struct hashTable* tmp; // 定义指向 hashTable 的指针变量 tmp// [参数解读] hashtable:哈希表,&ikey:key 的地址,tmp:输出 key 的结构 HASH_FIND_INT(hashtable, &ikey, tmp);return tmp; // 返回 key 的结构,若 key 不存在则返回 NULL
}// 哈希表中不存在 key 为 target - x 的结点时才会执行此函数
void insert(int ikey, int ival) {// 查找 hashtable 中是否已经存在目标 key:xstruct hashTable* it = find(ikey);if (it == NULL) { // 若不存在目标 key:x,将 x ,x 对应的下标 i 作为键值对插入 hashtable// 为结点申请内存空间struct hashTable* tmp = malloc(sizeof(struct hashTable));// 将 x,x 对应的下标 i 存到 tmp 中,ikey:x,val:itmp->key = ikey, tmp->val = ival;// [参数解读] hashtable:哈希表,key:键字段名称,tmp:指向要添加的结构的指针HASH_ADD_INT(hashtable, key, tmp);} else { // 若存在目标 key:xit->val = ival; // 将 x 对应的下标 i 插入 key:x 对应的 val}
}// 整数数组 nums,整数目标值:target
int* twoSum(int* nums, int numsSize, int target, int* returnSize) {hashtable = NULL; // hashtable 指针初始为空for (int i = 0; i < numsSize; i++) { // i 遍历 nums// 寻找 key 为 target - x 对应的哈希结点struct hashTable* it = find(target - nums[i]);if (it != NULL) { // 找到了,直接返回 x 和 target - x 数组下标int* ret = malloc(sizeof(int) * 2); // 为答案数组开辟两个空间ret[0] = it->val, ret[1] = i; // 答案数组分别存放 target - x,x 的下标*returnSize = 2; // 答案数组的大小为 2return ret; // 返回答案数组}// 未找到,将 x,i 作为新的键值对插入哈希表insert(nums[i], i);}// 没有找到 x,target - x 的情况*returnSize = 0; // 答案数组大小置 0return NULL; // 返回 NULL
}
class Solution {
public:// 整数数组:nums,整数目标值:targetvector twoSum(vector& nums, int target) {// 用 unordered_map 容器创建哈希表,键:int,值:int,变量名:hashtableunordered_map hashtable; // [哈希表结构] key:值,val:值对应在数组里的下标for (int i = 0; i < nums.size(); ++i) {// auto 的作用:根据后面变量的值推测变量的类型,此处等价于 unordered_map it = hashtable.find(target - nums[i]);auto it = hashtable.find(target - nums[i]);// unordered_map::end() 返回一个迭代器,指向 unordered_map 容器中最后一个元素的位置if (it != hashtable.end()) { // 若哈希表中存在 key 为 target - x 的键值对return {it->second, i}; // 返回 target - x,x 的下标}// 不存在,则将键值对 key:x,val:i 插入哈希表hashtable[nums[i]] = i;}// 没有找到 x,target - x 的情况return {};}
};
class Solution:// 整数数组:nums,整数目标值:targetdef twoSum(self, nums: List[int], target: int) -> List[int]:hashtable = dict() # Python 中的字典类型相当于哈希表for i, num in enumerate(nums): # i 遍历 numsif target - num in hashtable: # 字典里存在 key:target - xreturn [hashtable[target - num], i] # 返回 target - x,x 的下标# 字典里不存在 key:target - x,将键值对 key:nums[i],value:i 写入字典hashtable[nums[i]] = i # 未找到 x,target - x 则返回空值return []
class Solution {public int[] twoSum(int[] nums, int target) {Map hashtable = new HashMap();for (int i = 0; i < nums.length; ++i) {if (hashtable.containsKey(target - nums[i])) {return new int[]{hashtable.get(target - nums[i]), i};}hashtable.put(nums[i], i);}return new int[0];}
}
func twoSum(nums []int, target int) []int {hashTable := map[int]int{}for i, x := range nums {if p, ok := hashTable[target-x]; ok {return []int{p, i}}hashTable[x] = i}return nil
}
下一篇:曼联是什么?