twoSum

Problem

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.

Example

Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

Solution 1
 vector<int> twoSum(vector<int>& nums, int target) {
        size_t mLength = nums.size();
        vector<int> mVec;
        mVec.resize(2);
        
        for (int i = 0; i < mLength - 1; i++){
            for(int j = i + 1; j < mLength; j++){
                if (nums[i] + nums[j] == target){
                    mVec[0] = i;
                    mVec[1] = j;
                    return mVec;
                }
            }//inside-for
        }//for
   }
Solution 2
std::vector<int> twoSum(std::vector<int>& nums, int target) {
        std::map<int, int> mMap;
        std::vector<int> result;
        result.reserve(2);

        for (int i = 0; i < nums.size(); i++) {
            int complement = target - nums[i];
            
            //map.find return iterator
            auto iter =  mMap.find(complement);
        
            if (iter != mMap.end()){
                result.push_back(mMap[complement]);
                result.push_back(i);
                return result;
            }
            mMap.insert(std::pair<int, int>(nums[i], i));
        }
    }//twoSum
  • Solution2是一种贪心策略,对数组进行迭代,且迭代过程通过Map辅助进行问题求解。
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 13,398评论 0 23
  • 一候桃始华,二候仓庚鸣,三候鹰化鸠 今日满满收获,第一次绕杨凌骑行,第一次摘了草莓,第一次和玉婷 吴倩 曾沙 晶媛...
    biubiu咂咂阅读 689评论 0 0
  • 大学上课确实挺无聊,甚至可以这么说,毫无新鲜感可言。于是,刷微博成了许多大学生闲暇追求新鲜感的习惯,特别是是在课件...
    莹火石头dy阅读 4,241评论 0 2
  • 有时候会猛然的警醒 觉得时光匆匆有太多心愿未了 恨不得不眠不休 把逝去的光阴都追回来 有时消沉且懈怠 任无数个清风...
    丁_香阅读 3,177评论 43 41
  • 记录大学第一次月考。
    厉害的啊依阅读 1,456评论 1 1