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
本来以为有简便的算法,先将数组排了下序,发现之前的下标找不到了....用了最简单的方法来做这道题。我在想是不是可以通过自己写一个排序将原先的数组的下标放到一个数组,用于记录排序前该元素的初始位置是多少。这样排序后的工作就少一些了。
代码:
public class Solution {
public int[] twoSum(int[] nums, int target) {
int res [] = new int [2];
for(int i=0;i<nums.length-1;i++){
for(int j=i+1;j<nums.length;j++){
if(nums[i]+nums[j]== target)
{
res[0]=i+1;
res[1]=j+1;
return res;
}
}
}
return res;
}
}