lleetcode 1 two sum c++

Problem describe:https://leetcode.com/problems/two-sum/

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.

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

AC code :

1.Bruth Algorithm

 1 class Solution {
 2 public:
 3     vector<int> twoSum(vector<int>& nums,int target) {
 4         vector<int> res;
 5         for(int i = 0;i < nums.size();i++)
 6             for(int j = i + 1;j < nums.size();j++)
 7                 if(nums[i]+nums[j]==target)
 8                 {
 9                     res.push_back(i);
10                     res.push_back(j);
11                 }
12         return res;
13                     
14     }
15 };

2.Hashmap

 1 class Solution {
 2 public:
 3     vector<int> twoSum(vector<int>& nums,int target) {
 4         vector<int> res;
 5         unordered_map<int,int> map;
 6         for(int i = 0; i < nums.size();i++)
 7         {
 8             map[nums[i]] = i;
 9         }
10         for(int i = 0;i < nums.size();i++)
11         {
12             int left = target - nums[i];
13             if(map.count(left) && i <  map[left])
14             {
15                 res.push_back(i);
16                 res.push_back(map[left]);
17             }        
18         } 
19         return res;
20     }
21 };

相关文章

本程序的编译和运行环境如下(如果有运行方面的问题欢迎在评...
水了一学期的院选修,万万没想到期末考试还有比较硬核的编程...
补充一下,先前文章末尾给出的下载链接的完整代码含有部分C&...
思路如标题所说采用模N取余法,难点是这个除法过程如何实现。...
本篇博客有更新!!!更新后效果图如下: 文章末尾的完整代码...
刚开始学习模块化程序设计时,估计大家都被形参和实参搞迷糊...