上完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");
}
};

  

哎!又菜又懒,没救了。

C++ leetcode::two sum的更多相关文章

  1. LeetCode:Path Sum I II

    LeetCode:Path Sum Given a binary tree and a sum, determine if the tree has a root-to-leaf path such ...

  2. 剑指offer 65. 不用加减乘除做加法(Leetcode 371. Sum of Two Integers)

    剑指offer 65. 不用加减乘除做加法(Leetcode 371. Sum of Two Integers) https://leetcode.com/problems/sum-of-two-in ...

  3. [LeetCode] Path Sum III 二叉树的路径和之三

    You are given a binary tree in which each node contains an integer value. Find the number of paths t ...

  4. [LeetCode] Combination Sum IV 组合之和之四

    Given an integer array with all positive numbers and no duplicates, find the number of possible comb ...

  5. [LeetCode] Max Sum of Rectangle No Larger Than K 最大矩阵和不超过K

    Given a non-empty 2D matrix matrix and an integer k, find the max sum of a rectangle in the matrix s ...

  6. [LeetCode] Range Sum Query 2D - Mutable 二维区域和检索 - 可变

    Given a 2D matrix matrix, find the sum of the elements inside the rectangle defined by its upper lef ...

  7. [LeetCode] Range Sum Query - Mutable 区域和检索 - 可变

    Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive ...

  8. [LeetCode] Range Sum Query 2D - Immutable 二维区域和检索 - 不可变

    Given a 2D matrix matrix, find the sum of the elements inside the rectangle defined by its upper lef ...

  9. [LeetCode] Range Sum Query - Immutable 区域和检索 - 不可变

    Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive ...

  10. [LeetCode] Combination Sum III 组合之和之三

    Find all possible combinations of k numbers that add up to a number n, given that only numbers from ...

随机推荐

  1. 传输SO10 (SO10 Transport)

    传输SO10 (SO10 Transport) 方法一.   手工添加到请求里面,格式为: R3TR TEXT text object, name, ID, language   方法二.使用程序:R ...

  2. HDU 4496 D-City(逆向并查集)

    http://acm.hdu.edu.cn/showproblem.php?pid=4496 题意: 给出n个顶点m条边的图,每次选择一条边删去,求每次删边后的连通块个数. 思路: 离线处理删边,从后 ...

  3. POJ 3693 Maximum repetition substring(连续重复子串)

    http://poj.org/problem?id=3693 题意:给定一个字符串,求重复次数最多的连续重复子串. 思路: 这道题确实是搞了很久,首先枚举连续子串的长度L,那么子串肯定包含了r[k], ...

  4. C# widget

    Invoke(Delegate)的用法: //例如,要实时update窗体.如果在另一个线程中update,那么可以直接update(可以不在新线程中):也可以在Delegate中给出upate,然后 ...

  5. EF Code First 整不明白 继续完善

    1.Add-Migration RenameDesc  要修改列名先用这个,然后把要修改的列名手动修改一下.  多出这个文件 public partial class RenameDesc : DbM ...

  6. 获得WebBrowser中的图片数据

    /// <summary> /// 获取WebBrowser指定的图片 /// </summary> /// <param name="webBrowser&q ...

  7. 数据库备份出现警告:Warning: Using a password on the command line interface can be insecure. Warning: A partial dump from a server that has GTIDs will by default include the GTIDs of all transactions, even thos

    1.先来看原备份数据库语句: mysqldump -h 127.0.0.1 -uroot -ppassword database > /usr/microStorage/dbbackup/cap ...

  8. "ProgrammerHome"项目笔记

    系统目的: 1.技术练习:把平时不用的,重要技术栈,在此项目中打磨(java.python.算法.系统构架) 2.新技术(工具)应用:有些平时想做,想实现的技术,可以在这里实现.而且以微服务的方式,轻 ...

  9. Could not find com.android.tools.build:aapt2:3.2.1-4818971.

    Could not find com.android.tools.build:aapt2:-. Searched in the following locations: file:/H:/Androi ...

  10. php中if(\$a==\$b)和if(\$a=\$b)什么区别?

    <?php // if($a==$b)和if($a=$b)什么区别? $a = 1; $b = 1; if ($a == $b) { // 通过 echo '通过'.PHP_EOL; } if ...