【LeetCode】001. TwoSum
2024-09-01 07:29:38
题目:
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;
}
};
最新文章
- react native改变app的图标和名称
- printf函数
- 用JS识别各版本浏览器
- C# 静态类与非静态类、静态成员的区别
- C语言实现贪吃蛇源码
- HTML中IFrame父窗口与子窗口相互操作
- atitit.GMT UTC Catitit.GMT UTC CST DST CET 星期 月份 节日 时间的不同本质and起源
- backbone杂记
- GTX 680 Kepler
- centos -bash-4.1$ 不显示用户名路径
- Struts, Namespace用法
- es6整理
- 初识Mybatis框架,实现增删改查等操作
- Linux Security模块
- 大到可以小说的Y组合子(零)
- poj 2681 字符串
- pt-show-grants的用法
- pip错误-failed to create process/fatal error in launcher
- 查看selinux与关闭方法
- 洛谷P1315 观光公交