LeetCode 1.Two Sum(easy)

 

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].

 

解题思路:

这个题一开始,想要直接用暴力方法,对每一组数字进行遍历,但是这个方法的时间复杂度太高了O(n^2).所以我想了想,用python做的话,可以用字典,将数组放入字典中作为key,然后计算target-key得到满足题意所需的数,当这个数能在字典的key中找到,就说明有,就输出对应的位置。

class Solution:
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        newnum={}
        count=0
        for number in nums:
            neednum=target-number
            if neednum in newnum:
                return (newnum[neednum], count)
            newnum[number]=count
            count+=1 

做完了以后,在Solution里边看到有个更加简洁的方法,不需要申请字典dict,直接target-a,判断nums里边是否存在这个数,有的话输出位置。

index = 0
    while(nums):
        a = nums.pop(0)
        b = target - a
        if b in nums:
            return [index, nums.index(b)+index+1]
        index += 1 

C++版:

因为python的方法是用dict,所以想到在c++中也可以用类似的结构。在STL中有个map容器,也是key-value结构,所以可以  用上边的python版相同的思路来解决问题。

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

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值