[LeetCode OJ][001]Two Sum

给定一个整数数组,从中寻找两个数使他们的和为指定的数值。
函数twoSum应返回和为目标数值的两个数的下标,index1必须小于index2。注意返回值中index1和index2都不是从零开始的。
假设每个输入都有唯一解。
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2

我的想法:

  • 数组不是有序的,因此必须顺序遍历
  • 数组可能存在负值,因此不能滤掉掉大于target的元素
  • 对每一个元素i查找target - i是否存在于数组中
  • 查找依据int型,因此可以用set来查找。
  • Python的for-in和C++的set::iterator(是bidirectional iterator)都不能直接获得下标。因此改用map储存下标。

Python2版(58ms):

class Solution:
    # @return a tuple, (index1, index2)
    def twoSum(self, num, target):
        numset = {}
        for index1 in range(len(num)):
            current = num[index1]
            index2 = numset.get(target - current)
            if index2 is None:
                numset[current] = index1
            else:
                return index2 + 1, index1 + 1

C++11版(19ms):

class Solution
{
public:
    vector<int> twoSum(vector<int> &numbers, int target)
    {
        std::vector<int> answer;
        std::unordered_map<int, int> numset;
        std::unordered_map<int, int>::iterator it;

        for(int i = numbers.size() - 1; i >= 0; --i)
        {
            int &current = numbers[i];
            if((it = numset.find(target - current)) != numset.end())
            {
                answer.push_back(i + 1);
                answer.push_back(it->second + 1);
                return std::move(answer);
            }
            else
            {
                numset.insert(std::pair<int, int>(current, i));
            }
        }
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值