Two Sum —— leetcode
2016-09-04 18:51
351 查看
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.
Example:
本题要求我们找出一串数字中的其中两个,它们相加后等于特定值。需注意以下几点:
1、由于本题数据量较大,用两层循环穷举所有情况将导致超时
2、由于数字可能有负数,所以不能直接用作下标
3、序列中可能有相同的数字
我设计的算法(复杂度为O(n))如下:
1、创建一个足够大的数组m,初始化为0,对于序列中的每个数字a,m[a + 10000]++;(避免负数)
2、对于序列中的每个数字a,判断target - a是否满足要求,若满足,a和target - a即为符合要求的数字
3、再遍历一遍所给序列,找到符合要求数字的下标
程序代码如下所示:
You may assume that each input would have exactly one solution.
Example:
Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].
本题要求我们找出一串数字中的其中两个,它们相加后等于特定值。需注意以下几点:
1、由于本题数据量较大,用两层循环穷举所有情况将导致超时
2、由于数字可能有负数,所以不能直接用作下标
3、序列中可能有相同的数字
我设计的算法(复杂度为O(n))如下:
1、创建一个足够大的数组m,初始化为0,对于序列中的每个数字a,m[a + 10000]++;(避免负数)
2、对于序列中的每个数字a,判断target - a是否满足要求,若满足,a和target - a即为符合要求的数字
3、再遍历一遍所给序列,找到符合要求数字的下标
程序代码如下所示:
int m[20000]; class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { vector<int> v; memset(m,0,sizeof(m)); for(int i=0;i<nums.size();++i){ m[nums[i]+10000]++; } int a,b; for(int i=0;i<nums.size();++i){ if(nums[i] == target - nums[i] && m[nums[i] + 10000] >= 2){ a = b = nums[i]; break; } else if(m[nums[i] + 10000] >= 1 && m[target - nums[i] + 10000] >= 1 && nums[i] != target - nums[i]){ a = nums[i]; b = target - nums[i]; break; } } for(int i=0,j=0;i<nums.size() && j<2; ++i){ if(nums[i] == a || nums[i] == b){ v.push_back(i); j++; } } return v; } };
相关文章推荐
- LeetCode 371(Sum of Two Integers)
- LeetCode-Two Sum III - Data structure design
- [Leetcode]Two Sum II - Input array is sorted
- leetcode:数组之Two Sum
- leetcode twoSum
- leetcode解题报告(22):Two Sum II - Input array is sorted
- leetcode371-----Sum of Two Integers
- LeetCode修仙:Two Sum详解
- [LeetCode] Two Sum II - Input array is sorted
- Leetcode_Two Sum II - Input array is sorted
- Leetcode Two Sum
- 【leetcode】two-sum
- Leetcode_001_Two_Sum
- leetcode[Two Sum IV - Input is a BST]//待整理多种解法
- LeetCode之Two Sum II - Input array is sorted
- Leetcode 371 :Sum of Two Integers
- LeetCode (1)Two Sum | LeetCode
- [LeetCode]题解(python):001-Two-Sum
- LeetCode 653: Two Sum IV - Input is a BST
- LeetCode_1_TwoSum(Java Code)