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
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
问题分析:题目的目标就是返回数组中的元素之和为目标元素的二个元素对应的下标。常规的解法就是采用双重循环的方式,时间复杂度为O(n*n),代码比较简单,实现如下:
public class Solution {
public int[] twoSum(int[] nums, int target) {
int[] indexs=new int[2];
int m=0,n=0;
for(int i=0;i<nums.length-1;i++)
for(int j=i+1;j<nums.length;j++){
if(nums[i]+nums[j]==target){
m=i+1;
n=j+1;
}
}
indexs[0]=m;
indexs[1]=n;
return indexs;
}
}
但是,还可以进一步的优化,将时间复杂度降为O(n),采用一个map来保存,key用来保存值,value用来保存index,实现代码如下:
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> indexs;
map<int,int> mapnums;
for(int i=0;i<nums.size();i++){
mapnums[nums[i]]=i;
}
for(int i=0;i<nums.size();i++){
if(mapnums[target-nums[i]]) {
indexs.push_back(i+1);
indexs.push_back(mapnums[target-nums[i]]+1);
return indexs;
}
}
return indexs;
}
};