LeetCode——01 Two Sum

Two Sum

  Total Accepted: 23868  Total Submissions: 130908 My Submissions

Given an array of integers, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

You may assume that each input would have exactly one solution.

Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2

此题为我在LeetCode上做的第一个题目,由于和以前OJ的形式有点不同,开始出了很多错误。

一开始暴力解决,导致超时。后来自己写了个快速排序的算法,先对数据进行排序,发现还是超时。

后来发现,在LeetCode中可以直接使用C++ STL的一些容器,所以题目很容易就AC了。

以下是暴力方法:

class Solution {
public:
    vector<int> twoSum(vector<int> &numbers, int target) {
        int notfound = 1, i, j;
        for(i = 0; i < numbers.size() && notfound; ++i)
            for(j = i+1; j < numbers.size(); ++j)
                if(numbers[i] + numbers[j] == target)
                {
                    notfound = 0;
                    break;
                }
        vector<int> ret;
        ret.push_back(i+1);
        ret.push_back(j+1);
        return ret;
    }
};

下面的算法用map保存输入的数据,map会自动将数据排序,由于题目指出“ You may assume that each input would have exactly one solution.”由此可以判断出输入的数据里面不会有重复的,那么用map的时候不用考虑重复的情况。

class Solution {
public:
    vector<int> twoSum(vector<int> &numbers, int target) {
        map<int, int> mp;
        for(int i = 0; i < numbers.size(); ++i)
            mp[numbers[i]] = i + 1;
            
        for(int i = 0; i < numbers.size(); ++i)
        {
            int b = target - numbers[i];
            int j = mp[b];
            if(j > 0 && i + 1 != j)
            {
                vector<int> ret;
                ret.push_back(i+1);
                ret.push_back(j);
                return ret;
            }
        }
    }
};






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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值