[C++]LeetCode: 14 Two Sum

题目:

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

思路:最笨的办法,遍历数组。

Attention: 返回的索引是数组索引加1.

复杂度:

O(n2) runtime, O(1) space – Brute force

超时:

Submission Result: Time Limit Exceeded

Last executed input: [0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,46,48,50,52,54,56,58,60,62,64,66,68,70,72,74,76,78,

Code:
注:!!注意函数的输入形参。
vector<int> twoSum(vector<int> &numbers, int target)
<span style="color:#ff6666;">verctor<int> &numbers是引用类型形参</span><span style="color: rgb(51, 51, 51);">,引用形参直接关联到其所绑定的对象,而并非这些对象的副本。</span>
class Solution {
public:
    vector<int> twoSum(vector<int> &numbers, int target) {
        //输入是整数数组,并给定目标值。输出和为目标值的两个索引。
        //并且题目答案假设是唯一解
        //利用遍历的方法 最笨的办法
        vector<int> result;
        
        //遍历输入数组
        for(int i = 0; i <= numbers.size(); i++)
        {
            for(int j = i+1; j <= numbers.size(); j++)
            {
                if(target == numbers[i] + numbers[j])
                {
                    result.push_back(i+1);
                    result.push_back(j+1);
                    break;
                }
            }
        }
        return result;
    }
};

优化方法一:Hash表
复杂度:O(n) runtime, O(n) space – Hash table
思路2:改变数据结构,利用map
Attention: 注意ret的索引是hash[x]+ 1 和 i。
AC Code:
class Solution {
public:
    vector<int> twoSum(vector<int> &numbers, int target) {
        //换一个数据结构 map
        map<int, int> hash;
        vector<int> ret;
        
        for(int i = 0; i < numbers.size(); i++)
        {
            //x即待寻找的匹配值
            int x = target - numbers[i];
            // map<K,V> m ; m.find(k) 如果m容器中存在按k索引的元素,则返回指向该元素的迭代器,否则,返回超出末端迭代器。m.end()
            if(hash.find(x) != hash.end())
            {
                ret.push_back(hash[x] + 1);
                ret.push_back(i + 1);
                return ret;
            }
            //找不到目标值,就插入到map. map<key,value> 插入值:map<numbers[i], i>
            //不断地把数组存入map,方便下次查询是否有匹配值。
            hash[numbers[i]] = i;
        }
        
        return ret;
    }
};





评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值