功能: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:
Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].
鉴于自己初学Java,如Map、list等功能还未学习,只给出以下最简单的解决办法。(性能可能并不优秀)
public class Solution {
public int[] twoSum(int[] nums, int target) {
int[] result= new int[2];
for(int x=0;x<nums.length;x++)
{
inner:for(int y=x+1;y<nums.length;y++)
{
if((target-nums[x])==nums[y]) //判断当目标数减去外循环角标对应元素与内循环对应角标元素相同,即找到两加数。
{
result[0]=x;
result[1]=y;
break;//找到第一组符合数据后跳出外循环
}
}
}
return result;
}
}
输入:[1,2,4,4]
6
输出结果:[1,2]
可将此程序优化,修改为找出所有解,并返回所有解。
程序待给出。
当输入:[1,2,4,4]时,理论上有两个解[1,2]和[1,3]
程序修改为
class Demo { public static void main(String[] args) { int[] arrs = {1,2,4,4}; int target = 6; Solution a = new Solution(); a.twoSum(arrs,6); } } class Solution { public static void twoSum(int[] nums, int target) { int n = nums.length; int N = n*(n-1)/2; int[][] result= new int[N][2]; int i=0; for(int x=0;x<nums.length;x++) { for(int y=x+1;y<nums.length;y++) { if((target-nums[x])==nums[y]) //判断当目标数减去外循环角标对应元素与内循环对应角标元素相同,即找到两加数。 { result[i][0]=x; result[i++][1]=y; } else { result[i][0]=0; result[i++][1]=0; } } } for (int z=0;z<N ;z++ ) { for(int c=0;c<2;c++) { if (c!=1) { System.out.print(result[z][c]+","); }
} System.out.println();} } } 输出结果:0,0else System.out.print(result[z][c]);
0,0
0,0
1,2
1,3
0,0
程序可继续优化