LeetCode #1 Two Sum

问题描述

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

 

分析

        基本思路就是,将target与给定数组中的元素nums[i]做差,得到差值target-nums[i],则然后在数组中寻找此差值 ,按照题意,一定存在以为的两个不同的数,将其相加可以得到target.

       在实际实现时,需要注意,如果target是nums中的某元素nums[i]的二倍,则二者相减会得到 nums[i],但是题目要求不能使用相同的元素两次,所以如果找到这样的元素不能返回结果,而是要继续向下找。

代码

class Solution 
{
public:
    vector<int> twoSum(vector<int>& nums, int target) 
    {
        // 使用hash字典可以大大提高查找速度
        unordered_map<int, int> hash;
        vector<int> result(2, 0);
        
        for (int i = 0; i < nums.size(); i++)
        {
            // 在数组中寻找与target的差值
            if (hash.find( target - nums[i] ) != hash.end() )
            {
                // 如果找到了,则返回num[i]和另一个数的索引值
                result[0] = hash[ target - nums[i] ] - 1, result[1] = i;
                return result;
            }
            /*
            i = 0时,上面的if并不执行,将nums[0]的值和索引1存入map中
            i > 1时,如果在hash[0:i-1]中都没有找到,则当前nums[i]
            并不能找到一个值nums[j]与其相加等于target。要继续查找下一个元素,
            再继续将其与之前的所有元素,重复做差查找操作,直到找到。
            */
            hash[nums[i]] = i + 1;
        }
    }
};

        

转载于:https://my.oschina.net/yangkunxing/blog/875800

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值