LeetCode two sum
2017-06-03 11:29
495 查看
two sum
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.
找到一个数组里面和为给定的数的两个元素的指针。最简单地方法当然就是两层循环(N*2)代码如下
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; } };
在评论中看到了复杂度(N)的算法,用到了hashtable
class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { unordered_map<int,int> hash; vector<int> result; for(int i=0;i<nums.size();i++){ int numtofind=target-nums[i]; if(hash.find(numtofind)!=hash.end()){ result.push_back(hash[numtofind]); result.push_back(i); } hash[nums[i]]=i; } return result; } };之所以在循环内部插入键值对是为了避免结果重复
相关文章推荐
- leetcode Two Sum
- [LeetCode]Two Sum
- LeetCode之Two Sum
- [LeetCode] Two Sum, Solution
- Leetcode 1.Two Sum
- leetcode刷题笔记-two sum
- LeetCode --- 1. Two Sum
- LeetCode 1. Two Sum
- 【LeetCode】1. Two Sum
- LeetCode习题笔记——Two Sum
- 【Leetcode】001 Two Sum
- Two Sum[leetcode]
- leetcode - 1. Two Sum (java)
- LeetCode|Two Sum-java
- [leetcode, python] Two Sum 两数之和等于某数
- Two Sum -- LeetCode [数组类]
- [编程练习][Two Sum]<LeetCode-1>
- [LeetCode]--1. Two Sum
- LeetCode——01 Two Sum
- LeetCode1:Two Sum