【leetcode】1. Two Sum(Python & C++)

51 篇文章 1 订阅
50 篇文章 28 订阅

1. Two Sum

题目链接

1.1 题目描述:

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

1.2 解题思路:

  1. 思路一:第一个思路就是两次遍历,找到第一个元素,二次遍历其后面的元素,如果发现这两个元素的和为target,则两元素坐标push进vector。

  2. 思路二:利用map,一次遍历。在遍历时,获取target-当前遍历的元素的值,然后在map中查找是否有这个值,如果有,则将其map对应的值作为坐标值,连通遍历元素的坐标值一起push进vector;否则,则将当前遍历的这个元素的值与坐标放入map中。

1.3 C++代码:

1、思路一代码(233ms):

class Solution90 {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        vector<int>a;
        for (int i = 0; i < nums.size();i++)
        {
            for (int j = i + 1; j < nums.size();j++)
            {
                if (target == (nums[i] + nums[j]))
                {
                    a.push_back(i);
                    a.push_back(j);
                    return a;
                }
            }
        }
        return a;
    }
};

2、思路二代码(13ms):

class Solution90_1 {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        map<int, int>m;
        vector<int>a;
        for (int i = 0; i, nums.size();i++)
        {
            int tofind = target - nums[i];
            if (m.find(tofind)!=m.end())
            {
                a.push_back(m[tofind]);
                a.push_back(i);
                return a;
            }
            m[nums[i]] = i;
        }
        return a;
    }
};

1.4 Python代码:

1、思路一代码(5865ms):

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        a=[]
        for i in range(len(nums)):
            for j in range(i+1,len(nums)):
                if (nums[i]+nums[j])==target:
                    a.append(i)
                    a.append(j)
                    return a
        return a

2、思路二代码(39ms):

class Solution1(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        d={}
        for i in range(0,len(nums)):
            tofind=target-nums[i]
            if tofind in d:
                return [d[tofind],i]
            d[nums[i]]=i
        return a

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值