LeetCode-001题解
此题目摘自LeetCode001
Given an array of integers, find two numbers such that they add up to a specific target number. The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based. You may assume that each input would have exactly one solution. Input: numbers={2, 7, 11, 15}, target=9 Output: index1=1, index2=2
初看此题,首先想到的是暴力求解法,两个for循环嵌套,遍历寻找满足target的两个数。时间复杂度为O(n2)。其实此题还有一个O(n)的解法。十分巧妙。
先上代码(Java版本)
public class Solution { public int[] twoSum(int[] nums, int target) { int len = nums.length; Map<Integer, Integer> m = new HashMap<Integer, Integer>(); for(int i = 0; i < len; ++i){ if(m.get(nums[i]) != null){ return new int[] {(Integer)m.get(nums[i])+1, i + 1}; }else{ m.put(target - nums[i], i); } } return null; } }
代码很简短,但是理解起来比较抽象。大意是现在HashMap中寻找nums,没有找到,就把target-nums[i]以及下标i作为键值对存入m中。如果找到了,说明在m中有当前的数值刚好对应m存贮的target的余值。
另外贴上C++版本的题解。意义一样
class Solution { public: vector<int> twoSum(vector<int> &num, int target) { map<const int,int> m; int s = num.size(); for(int i=0;i<s;i++){ if(m.find(num[i])!= m.end()){ vector<int> vec; int pos = m[num[i]]; vec.insert(pos); vec.insert(i+1); return vec; } else{ m.insert(pair<int, int> (target -num[i], i+1)); } } } };