@CrazyHenry
2018-01-01T09:44:28.000000Z
字数 1567
阅读 1681
ddddLeetcode刷题
- Author:李英民 | Henry
- E-mail: li
_
yingmin@
outlookdot
com- Home: https://liyingmin.wixsite.com/henry
快速了解我: About Me
转载请保留上述引用内容,谢谢配合!
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] + nums1 = 2 + 7 = 9,
return [0, 1].
//Author: Li-Yingmin@https://liyingmin.wixsite.com/henry
//Email: li_yingmin@outlook.com
//Leetcode-1
//T(n)=O(n^2), S(n)=O(1)
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
//如果nums为空,返回空vector<int>对象
if (nums.empty()) return vector<int>();
//暴力法
for(decltype(nums.size()) indexi = 0; indexi < nums.size(); ++indexi)
for(decltype(nums.size()) indexj = indexi + 1; indexj< nums.size(); ++indexj)
{
if(nums[indexi] + nums[indexj] == target)
return vector<int>({indexi, indexj});
}
}
};
indexj=indexi + 1;
,因为两个数不能是同一下标。hash法:
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
//如果nums为空,返回空vector<int>对象
if (nums.empty()) return vector<int>();
//hash
unordered_map<int, int> mapping;
for(decltype(nums.size()) index = 0; index < nums.size(); ++index)
mapping[nums[index]] = index;
for(decltype(nums.size()) index = 0; index < nums.size(); ++index)
{
auto gap = target - nums[index];
if(mapping.find(gap) != mapping.end() && mapping[gap] != index)
return vector<int>({index, mapping[gap]});
}
}
};
classtype()
的方式返回临时对象,使用初值列表{}
,使用decltype
,使用auto
,完全符合C++11标准!高明!