题目:

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 = [, , , ], target = ,

Because nums[] + nums[] =  +  = ,
return [, ].

题解:

  首先想到暴力解,TLE(Time Limit Exceeded)问题先不考虑。从数组头开始,依次与其他元素比较,然后向后移动开始位置,需要注意的是返回的位置是从0开始的

Solution 1 (TLE)

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

  那怎样才能降低时间复杂度呢?这里有个经验准则,数组及字符串问题往往与(unordered)map、(unordered)set有关。这里使用unordered_map,用于查找;首先想到的思路是先遍历一遍数组,建立map映射表(元素值和位置的映射),然后再遍历一遍查找与当前元素之和为目标值的元素。建立m(数组元素)与m的位置的映射。

Solution 2

 class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int, int> m;
int n = nums.size();
vector<int> result;
for (int i = ; i < n; ++i) {
m[nums[i]] = i;
}
for (int i = ; i < n; ++i) {
int t = target - nums[i];
//m.find(t) != m.end() 可以用 m.count(t)代替
       //you may not use the same element twice.
if (m.find(t) != m.end() && m[t] != i) {
result.push_back(i);
result.push_back(m[t]);
break;
}
}
return result;
}
};

  有一种优化方法,思路是从数组头开始,依次将元素对应的加数加入map中,在建立映射的过程中,若发现map中已经存在了一个元素,由于这个元素的存在是之前的操作才加入到map中,及此元素对应的加数在之前已经存在,故直接返回即可。题设 each input would have exactly one solution。建立target-m与m的位置的映射。

Solution 3

 class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int, int> m;
vector<int> result;
for(int i=; i<nums.size(); i++)
{
if (m.find(nums[i])==m.end() )
{
m[target - nums[i]] = i;
}
else
{
result.push_back(m[nums[i]]);
result.push_back(i);
break;
}
}
return result;
}
};
 

最新文章

  1. react native改变app的图标和名称
  2. printf函数
  3. 用JS识别各版本浏览器
  4. C# 静态类与非静态类、静态成员的区别
  5. C语言实现贪吃蛇源码
  6. HTML中IFrame父窗口与子窗口相互操作
  7. atitit.GMT UTC Catitit.GMT UTC CST DST CET 星期 月份 节日 时间的不同本质and起源
  8. backbone杂记
  9. GTX 680 Kepler
  10. centos -bash-4.1$ 不显示用户名路径
  11. Struts, Namespace用法
  12. es6整理
  13. 初识Mybatis框架,实现增删改查等操作
  14. Linux Security模块
  15. 大到可以小说的Y组合子(零)
  16. poj 2681 字符串
  17. pt-show-grants的用法
  18. pip错误-failed to create process/fatal error in launcher
  19. 查看selinux与关闭方法
  20. 洛谷P1315 观光公交

热门文章

  1. PHP用星号隐藏部份用户名、身份证、IP、手机号、邮箱等实例
  2. 用matlab将nc数据读出来,写成二进制文件,然后用grads画图
  3. 【CodeChef】Factorial(n!末尾0的个数)
  4. Android 电容屏驱动
  5. 3D图形学理论入门指南
  6. 正则表达式 获取字符串内提取图片URL字符串
  7. iOS_多线程(二)
  8. WebLogic 12c 多节点Cluster静默安装
  9. html页面转JSP之后样式变化的问题
  10. NLP-特征选择