给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。
示例:
给定 nums = [2, 7, 11, 15], target = 9因为 nums[0] + nums[1] = 2 + 7 = 9所以返回 [0, 1]
c语言
- 暴力法
时间复杂度为O(n^2)int* twoSum(int* nums, int numsSize, int target, int* returnSize){if (numsSize == 0) return NULL;int *res = (int *)malloc(sizeof(int) * 2);for (int i = 0; i < numsSize - 1; i++) {for (int j = i + 1; j < numsSize; j++) {if (nums[i] + nums[j] == target) {res[0] = i;res[1] = j;*returnSize = 2;return res;}}}return NULL;}
c plus
- 哈希法
题解
anotherKey = target - nums[i]; 将想要的结果 当做 键值 存入 hash,值对应其索引。当 another 键值对应的值有值时,即 target + nums[i] = target;即一组结果
class Solution {public:vector<int> twoSum(vector<int>& nums, int target) {map<int, int> hash;vector<int> ret(2, -1);for (int i = 0; i < nums.size(); i++) {int anotherKey = target - nums[i];if (hash.count(anotherKey)) {ret[0] = hash[anotherKey];ret[1] = i;break;}hash[nums[i]] = i;}return ret;}};
- go 语言注意判断哈希表map[i]有没有对应的值,不能用map[i] != 0, 应该用v, ok := map[i]; ok {} 来判断。
func twoSum(nums []int, target int) []int {keyMap := make(map[int]int, len(nums))for i:= 0; i < len(nums); i++ {if v, ok := keyMap[target - nums[i]]; ok {return []int{i, v}}keyMap[nums[i]] = i //注意这里是将当前的值作为key存入map。}return []int{}}
