[关闭]
@CrazyHenry 2018-01-01T09:44:28.000000Z 字数 1567 阅读 1681

Leetcode1. Two Sum

ddddLeetcode刷题


75528-106.jpg-339.2kB

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].

我的代码:暴力法,O(n^2)

  1. //Author: Li-Yingmin@https://liyingmin.wixsite.com/henry
  2. //Email: li_yingmin@outlook.com
  3. //Leetcode-1
  4. //T(n)=O(n^2), S(n)=O(1)
  5. class Solution {
  6. public:
  7. vector<int> twoSum(vector<int>& nums, int target) {
  8. //如果nums为空,返回空vector<int>对象
  9. if (nums.empty()) return vector<int>();
  10. //暴力法
  11. for(decltype(nums.size()) indexi = 0; indexi < nums.size(); ++indexi)
  12. for(decltype(nums.size()) indexj = indexi + 1; indexj< nums.size(); ++indexj)
  13. {
  14. if(nums[indexi] + nums[indexj] == target)
  15. return vector<int>({indexi, indexj});
  16. }
  17. }
  18. };

image.png-77.6kB

优秀代码:hash,O(n)

image.png-77kB

hash法:

  1. class Solution {
  2. public:
  3. vector<int> twoSum(vector<int>& nums, int target) {
  4. //如果nums为空,返回空vector<int>对象
  5. if (nums.empty()) return vector<int>();
  6. //hash
  7. unordered_map<int, int> mapping;
  8. for(decltype(nums.size()) index = 0; index < nums.size(); ++index)
  9. mapping[nums[index]] = index;
  10. for(decltype(nums.size()) index = 0; index < nums.size(); ++index)
  11. {
  12. auto gap = target - nums[index];
  13. if(mapping.find(gap) != mapping.end() && mapping[gap] != index)
  14. return vector<int>({index, mapping[gap]});
  15. }
  16. }
  17. };

image.png-94.9kB

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注