• 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");
        }
    };
    

      

    哎!又菜又懒,没救了。
  • 相关阅读:
    springboot +mybatis 使用PageHelper实现分页,并带条件模糊查询
    jQuery设置点击选中样式,onmouseover和onmouseout事件
    Ajax跨域设置
    Java获取文章的上一篇/下一篇
    Python str / bytes / unicode 区别详解
    Python bytes 和 string 相互转换
    Python bytearray/bytes/string区别
    Python eval 与 exec 函数区别
    Python eval 与 exec 函数
    Python set list dict tuple 区别和相互转换
  • 原文地址:https://www.cnblogs.com/catpainter/p/8458492.html
Copyright © 2020-2023  润新知