C++ leetcode::two sum

本文通过三种不同方法解决“两数之和”问题,包括暴力解法、双指针法及使用哈希表的方法,并对比了它们的时间效率。

上完C++的课就在也没用过C++了,最近要找实习,发现自己没有一门语言称得上是熟练,所以就重新开始学C++。记录自己从入门到放弃的过程,论C++如何逼死花季少女。

题目: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.

大意就是,给一个vector和target,在vector中找到两个数加起来等于target。

没仔细想就提交了自己的暴力解法。运行时间238ms,果真菜的不行,这个题最好的成绩是3ms。

 

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

  

果断换一种解法,双指针法:将数组排序,用两个指针,i指向数组首元素,j指向数组尾元素,两个元素相加,大于target就j--,小于target就i--,找到正确的i、j之后,还要确定其在原数组中的下标,查找时要避免两个元素值相同时返回的下标也相同。例如:Input:[3,3]  6 ;Output:[0,0]  ; Expected:[0,1],提交之后运行时间为8ms

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        vector<int> result;
        vector<int> sortednums(nums);
        sort(sortednums.begin(),sortednums.end());
        int i = 0, j = sortednums.size()-1;
        while(i != j){
            if (sortednums[i] + sortednums[j] > target)
                j--;
            else if (sortednums[i] + sortednums[j] < target)
                i++;
            else
            {   
                vector<int>::iterator it =find(nums.begin(),nums.end(),sortednums[i]);
                i = distance(nums.begin(),it);
                nums[i] = nums[i] +1;
                it = find(nums.begin(),nums.end(),sortednums[j]);
                result.push_back(i);
                result.push_back(distance(nums.begin(),it));
                return result;
            }
        }
    }
};
第三种方法:用map查找,在把数组中元素向map中插入时,先判断target-nums[i]在不在map中,这样可以避免数组中的重复元素进map。提交之后10ms,比方法2慢,之后再分析复杂度吧。
class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        vector<int> result;
        map<int,int> hashtable;
        map<int,int>::iterator it;
        for(int i = 0; i!= nums.size(); i++)
        {   
            it = hashtable.find(target - nums[i]);
            if (it != hashtable.end())
            {
                result.push_back(it->second);
                result.push_back(i);
                return result;
            }
            else if (!hashtable.count(nums[i]))
                hashtable.insert(make_pair(nums[i], i));
        }
    }
};

  

大神的代码,3ms,先贴着,之后再分析。
static const auto __________ = []()
{
    ios::sync_with_stdio(false); 
    cin.tie(nullptr);
    return nullptr;
}();

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {  
        using SizeType = remove_reference_t<decltype(nums)>::size_type;
        using ValueToIndexMapType = unordered_map<int, SizeType>;
        ValueToIndexMapType map;
        vector<int> indices(2);
        for (SizeType index = 0; index < nums.size(); ++index)
        {
            const auto foundIterator = map.find(target - nums[index]);
            if (foundIterator != end(map) && foundIterator->second != index)
                return vector<int>{ index, foundIterator->second };
            else
                map.emplace(nums[index], index);    
        }
        throw std::runtime_error("Solution not found");
    }
};

  

哎!又菜又懒,没救了。

转载于:https://www.cnblogs.com/catpainter/p/8458492.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值