• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
正在努力成为一个优秀的废物
博客园    首页    新随笔    联系   管理    订阅  订阅
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");
    }
};

  

哎!又菜又懒,没救了。
posted on 2018-02-22 11:57  你算哪根小毛线  阅读(497)  评论(2)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3