英文:
"Unknown Error Occurred" using Java in Leetcode - Cannot Submit or Run -
问题
我是LeetCode的新手,在尝试运行我的代码时一直遇到错误。有人之前遇到过这种情况吗?我已经尝试了许多不同的方法,甚至使用了别人的代码,而那些代码是可以正常工作的。
```java
class Solution {
public int[] twoSum(int[] nums, int target) {
for (int i = 0; i < nums.length; i++) {
for (int j = i + 1; j < nums.length; j++) {
int complement = target - nums[i];
if (nums[j] == complement) {
return new int[] {i, j};
}
}
}
throw new IllegalArgumentException("找不到匹配");
}
}
这是我的代码。有人能帮帮我吗?
<details>
<summary>英文:</summary>
I am new on LeetCode, and continue to get an error when trying to run my code. Has anyone encountered this before. I have tried many different methods and even used other peoples code that has worked.
```java
class Solution {
public int[] twoSum(int[] nums, int target) {
for (int i = 0; i < nums.length; i++) {
for (int j = i + 1; j < nums.length; j++) {
int complement = target - nums[i];
if (nums[j] == complement) {
return new int[] {i, j};
}
}
}
throw new IllegalArgumentException("no match found");
}
}
<!-- end snippet -->
This is my code. Can anyone help me?
答案1
得分: 1
你的代码已经很好了,不过我们可以使用 HashMap 来更高效地解决这个问题:
public class Solution {
public static final int[] twoSum(
final int[] nums,
final int target
) {
int[] indices = new int[2];
HashMap<Integer, Integer> map = new HashMap<>();
for (int index = 0; index < nums.length; index++) {
if (map.get(target - nums[index]) != null) {
indices[1] = index;
indices[0] = map.get(target - nums[index]);
return indices;
}
map.put(nums[index], index);
}
return indices;
}
}
英文:
Your code works just fine, yet we can use a HashMap for solving the problem a bit more efficiently:
public class Solution {
public static final int[] twoSum(
final int[] nums,
final int target
) {
int[] indices = new int[2];
HashMap<Integer, Integer> map = new HashMap<>();
for (int index = 0; index < nums.length; index++) {
if (map.get(target - nums[index]) != null) {
indices[1] = index;
indices[0] = map.get(target - nums[index]);
return indices;
}
map.put(nums[index], index);
}
return indices;
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论