我正在尝试使用 Eclipse 做一个二和问题。我想使用一个数组并让程序执行标准递归以查看下面列出的数组中的任何整数是否可以加在一起等于我的目标总和 9。
这是我正在解决的问题,在实施我的策略时遇到了麻烦......(注意我已经尝试过对我的编码进行多种解释)
给定一个整数数组,返回两个数字的索引,使它们加起来等于一个特定的目标。
您可能会假设每个输入只有一个解决方案,并且您可能不会两次使用相同的元素。
例子:
给定 nums = [2, 7, 11, 15], target = 9,
因为 nums[0] + nums[1] = 2 + 7 = 9,返回 [0, 1]。
import java.util.ArrayList;
public class twoSumArray {
public twoSumArray(int[] nums, int target)
{
for(int i = 0; i < nums.length; i++)
{
for (int j = i + 1; j < nums.length; j++)
{
if (nums[j] == target - nums[i])
{
}
}
}
}
public static void main(String[] args) {
ArrayList<Integer>myArray = new ArrayList<Integer>();
myArray.add(2);
myArray.add(7);
myArray.add(11);
myArray.add(15);
int target = 9;
ArrayList<Integer> result = twoSum(myArray,target);
for(int j : result)
System.out.print("["+j+","+target+"]");
}
}
我试过的另一个代码......
class Solution {
public static int[] twoSum(int[] nums, int target)
{
for(int i = 0; i < nums.length; i++)
{
for (int j = i + 1; j < nums.length; j++)
{
if (nums[j] == target - nums[i])
{
return new int[] {i, j};
}
}
}
System.out.println(twoSum.Solution);
}
public static void main(String[] args) {
int[] nums = {2,7,11,15};
twoSum(nums , 9);
}
}
MYYA
料青山看我应如是
有只小跳蛙
慕工程0101907
相关分类