1. Two Sum

Question:
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.

Solution 1 (brute force)
就是最简单一个一个加过去,用两个for循环,时间复杂度为o(n^2)

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        int n =nums.size();
        vector<int> arr;  //存储和为target的下标
        int k=0;//用来计数
        for(int i=0;i<n;i++)
        {
            for(int j=i+1;j<n;j++)
            {
                if(nums[i]+nums[j]==target)
                {
                    arr.push_back(i);
                    arr.push_back(j);
                }
                    
            }
        }
        return arr;
    }
};

solution2 (hashmap)
这个解法最令我生气的是,好不容易我迈出了把hashmap从理论去实践这一步,但是hashmap却过时了???
呵呵呵呵
变成了unordered_map,unordered_map是key,value形式,但是内部是用哈希表实现的,和map不一样,map是用红黑树实现的

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        unordered_map <int,int> mp;
        //vector<int> ret;
        for(int i=0;i<nums.size();i++)
        {
            if(mp.find(target-nums[i])!=mp.end())
            {
                return {mp[target-nums[i]],i};
                //ret.push_back(i);
                //ret.push_back(mp[target-nums[i]]);
            }       
            //mp.insert(pair<int,int>(i,nums[i]));
            mp[nums[i]] = i;
        }
        //return ret;
        return { };
    }
};

只用一个unorder_map的话就是查找有没有,然后把数据放入mp,不理解的是mp.insert(pair<int,int>(i,nums[i]));这种插入方式会报错,明明这种方式也是合理的。
注释部分是用一个vector的数组来存储符合要求的下标,然后返回数组。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值