LeetCode 1.两数之和【力扣——C/C++/Python三种编程语言题解】

简介: LeetCode 1.两数之和【力扣——C/C++/Python三种编程语言题解】

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

你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。

你可以按任意顺序返回答案。

示例 1:

输入:nums = [2,7,11,15], target = 9

输出:[0,1]

解释:因为 nums[0] + nums[1] == 9 ,返回 [0, 1] 。

示例 2:

输入:nums = [3,2,4], target = 6

输出:[1,2]

示例 3:

输入:nums = [3,3], target = 6

输出:[0,1]

🏆C语言版

使用两层循环求解

/**
 * Note: The returned array must be malloced, assume caller calls free().
 */
int* twoSum(int* nums, int numsSize, int target, int* returnSize){
    int i = 0, j = 0;
    int* ret = (int *)malloc(2 * sizeof(int));
    for(i = 0; i < numsSize; i++)
    {
        for(j = i + 1; j < numsSize; j++)
        {
            if((nums[i] + nums[j]) == target)
            {
                *ret = i;
                *(ret + 1) = j;
            }
        }
    }
    *returnSize = 2;
    return ret;
}

🏆C++版

使用哈希,unordered_map底层实现为散列,相对于有序的map来说效率更高一些,因为unordered_map是无序的。

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        unordered_map<int, int> m;
        int i = 0;
        do
        {
            unordered_map<int, int>::iterator it = m.find(target - nums[i]);
            if(it != m.end())
            {
                return {it->second, i};
            }
            else
            {
                m.insert(pair<int, int>(nums[i], i));
        i++;
            }
        }while(i < nums.size());
        return {};
    }
};

🏆Python版

使用字典,在python中,字典就是散列

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        hashmap = {}
        for key, val in enumerate(nums):
            if target - val in hashmap:
                return [key, hashmap[target - val]]
            hashmap[val] = key


相关文章
|
15天前
|
机器学习/深度学习 开发框架 人工智能
探索C++的深邃世界:编程语言的魅力与实践
探索C++的深邃世界:编程语言的魅力与实践
|
1月前
|
人工智能 机器人 C++
【C++/Python】Windows用Swig实现C++调用Python(史上最简单详细,80岁看了都会操作)
【C++/Python】Windows用Swig实现C++调用Python(史上最简单详细,80岁看了都会操作)
|
29天前
【Leetcode】两数之和,给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 target 的那 两个 整数,并返回它们的数组下标。
【Leetcode】两数之和,给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 target 的那 两个 整数,并返回它们的数组下标。
|
1天前
|
存储 算法
【LeetCode力扣】单调栈解决Next Greater Number(下一个更大值)问题
【LeetCode力扣】单调栈解决Next Greater Number(下一个更大值)问题
4 0
|
1天前
|
Java
【LeetCode力扣】面试题 17.14. 最小K个数(top-k问题)
【LeetCode力扣】面试题 17.14. 最小K个数(top-k问题)
7 1
|
1天前
leetcode代码记录(两数之和
leetcode代码记录(两数之和
7 1
|
1天前
|
算法 C语言 C++
|
2天前
leetcode代码记录(有序数组两数之和
leetcode代码记录(有序数组两数之和
9 0
|
4天前
|
存储 算法
Leetcode 30天高效刷数据结构和算法 Day1 两数之和 —— 无序数组
给定一个无序整数数组和目标值,找出数组中和为目标值的两个数的下标。要求不重复且可按任意顺序返回。示例:输入nums = [2,7,11,15], target = 9,输出[0,1]。暴力解法时间复杂度O(n²),优化解法利用哈希表实现,时间复杂度O(n)。
16 0
|
12天前
|
算法
LeetCode-1:两数之和
LeetCode-1:两数之和