栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

Leetcode-两数之和

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Leetcode-两数之和

题目:

给定一个整数数组 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]
提示:
2 <= nums.length <= 104
-109 <= nums[i] <= 109
-109 <= target <= 109
只会存在一个有效答案

解题思路

两层遍历的方式,时间复杂度为O(n^2)。

C++实现
#include 
#include 
using namespace std;
class Solution 
{
public:
    vector temp;
    vector twoSum(vector& nums, int target) 
    {
        if(nums.size()<2||nums.size()>1e4||target<-1e9||target>1e9)
        {
            throw new std::invalid_argument("The list is out of range");
        }
        for(int i=0;i 
Python实现 
class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        result = []
        for i, each in enumerate(nums):
            if abs(target-each) >=0 and i not in result:
                try:
                    tmp = nums.index(target - each)
                    if tmp != i:
                        result.append(i)
                        result.append(tmp)
                except:
                    continue
        return result

进阶:你可以想出一个时间复杂度小于 O(n2) 的算法吗?
可以使用哈希表,也就是散列表,在C++中是map容器,Python就是字典。

C++实现
class Solution {
public:
    vector twoSum(vector& nums, int target) {
        map a;//提供一对一的hash
        vector b(2,-1);//用来承载结果,初始化一个大小为2,值为-1的容器b
        for(int i=0;i0)
            {
                b[0]=a[target-nums[i]];
                b[1]=i;
                break;
            }
            a[nums[i]]=i;//反过来放入map中,用来获取结果下标
        }
        return b;
    };
};
Python实现
class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        if len(nums) <= 1:
            return False
        buff_dict = {}
        for i in range(len(nums)):
            if nums[i] in buff_dict:
                return [buff_dict[nums[i]], i]
            else:
                buff_dict[target - nums[i]] = i
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/339644.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号