[leetcode] Two Sum

Question:

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

分析:

法一:

要从一个数组里找两个元素的和等于目标值,简单的做法就是定义两个索引依次查找求和,等于目标值后存入数组返回即可。

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

法二:

两个for循环时间复杂度达到O(n2),对于元素较多的数组效率极低,可以用哈希表来建立映射,对于nums中的每个元素,用其下标建立映射,遍历nums,如果target-nums[i]能在在map中找到对应的映射,且不与nums[i]在map中对应的映射相同,则就找到了这两个数,将下标依次存入res中即可。只用到一个for循环,时间复杂度为O(n)。

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        int len = nums.size();
        vector<int>res;
        unordered_map<int , int>m;
        for(int i=0; i < len; i++)
            m[nums[i]] = i;
        for(int i=0; i < len; i++)
        {
            int t = target - nums[i];
            if(m.count(t) && m[t] != i)
            {
                res.push_back(i);
                res.push_back(m[t]);
                break;
            }
        }       
        return res;
    }
};

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值