给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。
示例:

  1. 给定 nums = [2, 7, 11, 15], target = 9
  2. 因为 nums[0] + nums[1] = 2 + 7 = 9
  3. 所以返回 [0, 1]

c语言


  • 暴力法
    时间复杂度为O(n^2)
    1. int* twoSum(int* nums, int numsSize, int target, int* returnSize){
    2. if (numsSize == 0) return NULL;
    3. int *res = (int *)malloc(sizeof(int) * 2);
    4. for (int i = 0; i < numsSize - 1; i++) {
    5. for (int j = i + 1; j < numsSize; j++) {
    6. if (nums[i] + nums[j] == target) {
    7. res[0] = i;
    8. res[1] = j;
    9. *returnSize = 2;
    10. return res;
    11. }
    12. }
    13. }
    14. return NULL;
    15. }

c plus


  • 哈希法

题解
anotherKey = target - nums[i]; 将想要的结果 当做 键值 存入 hash,值对应其索引。当 another 键值对应的值有值时,即 target + nums[i] = target;即一组结果

  1. class Solution {
  2. public:
  3. vector<int> twoSum(vector<int>& nums, int target) {
  4. map<int, int> hash;
  5. vector<int> ret(2, -1);
  6. for (int i = 0; i < nums.size(); i++) {
  7. int anotherKey = target - nums[i];
  8. if (hash.count(anotherKey)) {
  9. ret[0] = hash[anotherKey];
  10. ret[1] = i;
  11. break;
  12. }
  13. hash[nums[i]] = i;
  14. }
  15. return ret;
  16. }
  17. };
  • go 语言注意判断哈希表map[i]有没有对应的值,不能用map[i] != 0, 应该用v, ok := map[i]; ok {} 来判断。
    1. func twoSum(nums []int, target int) []int {
    2. keyMap := make(map[int]int, len(nums))
    3. for i:= 0; i < len(nums); i++ {
    4. if v, ok := keyMap[target - nums[i]]; ok {
    5. return []int{i, v}
    6. }
    7. keyMap[nums[i]] = i //注意这里是将当前的值作为key存入map。
    8. }
    9. return []int{}
    10. }