我试图用Java编写一个(暴力)解决方案来解决这个问题:
import java.lang.*;
public class TwoSum {
public 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};
}
}
}
}
throw new IllegalArgumentException("No two sum solution");
}
但是,当我尝试编译它时,我收到以下错误:
/home/kurt/Documents/Algorithms/TwoSum.java:13: error: illegal start of type
throw new IllegalArgumentException("No two sum solution");
^
/home/kurt/Documents/Algorithms/TwoSum.java:13: error: ';' expected
throw new IllegalArgumentException("No two sum solution");
^
/home/kurt/Documents/Algorithms/TwoSum.java:13: error: invalid method declaration; return type required
throw new IllegalArgumentException("No two sum solution");
^
/home/kurt/Documents/Algorithms/TwoSum.java:13: error: illegal start of type
throw new IllegalArgumentException("No two sum solution");
^
4 errors
[Finished in 0.8s with exit code 1]
我有点难过可能导致错误的原因? (我从示例代码段中获取了代码,但没有注意到任何差异)。
答案 0 :(得分:1)
使用以下代码:
evaluate=False
在这种情况下,import java.lang.*;
public class TwoSum {
public 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};
}
}
}
throw new IllegalArgumentException("No two sum solution");
}
}
是内部方法。