leetcode 1.两数之和(暴力&哈希)

1.题目链接

https://leetcode-cn.com/problems/two-sum/

2.题目描述

给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。

你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。

示例:

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

3.解题思路

3.1暴力实现

遍历每个数组,看是否满足nums[i] + nums[j]) == target

C语言代码实现

/**
 * Note: The returned array must be malloced, assume caller calls free().
 */
int* twoSum(int* nums, int numsSize, int target, int* returnSize){

    static int a[2] = {0};
    
    for(int i = 0; i < numsSize-1; i++)
    {
        for(int j = i + 1; j < numsSize; j++)
        {
            if((nums[i] + nums[j]) == target) {
                a[0] = i;
                a[1] = j;
                *returnSize = 2;
                return a;
            }    
        }    
    }
    return a;
}

3.2哈希表实现

遍历数组 numsi 为当前下标,每个值都判断map中是否存在 target-nums[i] key 值,如果存在则为target - nums[i]i,否则将当前的 (nums[i],i) 存入 map 中,继续遍历直到找到为止。

3.2.1 C语言代码实现

/**
 * Note: The returned array must be malloced, assume caller calls free().
 */
int map(int*nums, int numsSize, int data, int index) {
    int i = 0;
    for (i = 0; i < numsSize; i++) {
        if (nums[i] == data && i != index)
            break;
    }
    return i;
}
int* twoSum(int* nums, int numsSize, int target, int* returnSize){
    int tmp, j;
    static int res[2] = {0};
    *returnSize = 2;
    for (int i = 0; i < numsSize; i++) {
        tmp = target - nums[i];
        j = map(nums, numsSize, tmp, i);
        if (j < numsSize) {
            res[0] = i;
            res[1] = j;
            return res; 
        }
    }
    return res;
}

提交记录

 3.2.2 C++代码实现

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        unordered_map<intint> hash;
        for (int i = 0; i < nums.size(); i++) {
            if (hash.count(target - nums[i]))
                return {hash[target - nums[i]], i};
            hash[nums[i]] = i;
        }
        return {-1, -1};
    }
};

提交记录

 3.2.3 python3代码实现

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        hash = {}
        for i in range(len(nums)):
            tmp = target - nums[i]
            if tmp in hash:
                return [hash[tmp], i]
            hash[nums[i]] = i

提交记录

猜你喜欢

转载自www.cnblogs.com/zygote/p/13192731.html