public int[] twoSum(int[] nums, int target) { Map<Integer, Integer> map = new HashMap<Integer, Integer>(); for (int i = 0; i < nums.length; i++) { int complement = target - nums[i]; if (map.containsKey(complement)) { return new int[]{map.get(complement), i}; } map.put(nums[i], i); } return new int[] {}; }使用该代码优化完成
时间: 2024-03-09 17:47:03 浏览: 30
这个代码已经很优化了,不过我们可以稍微做一些改进。以下是优化后的代码:
```java
public static int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
int complement = target - nums[i];
if (map.containsKey(complement)) {
return new int[]{map.get(complement), i};
}
map.put(nums[i], i);
}
throw new IllegalArgumentException("No two sum solution");
}
```
在这个代码中,我们将返回一个抛出异常的语句替换了原来的返回空数组的语句。这样做的好处是,如果没有找到符合条件的结果,程序会立即停止并抛出异常,避免了后续程序可能会出现的空指针异常等问题。
希望这个优化后的代码可以更好地帮助您解决问题!
相关问题
测试这段代码public int[] twoSum(int[] nums, int target) { Map<Integer, Integer> hashtable = new HashMap<Integer, Integer>(); for (int i = 0; i < nums.length; ++i) { if (hashtable.containsKey(target - nums[i])) { return new int[]{hashtable.get(target - nums[i]), i}; } hashtable.put(nums[i], i); } return new int[0]; }
这段代码是一个方法,需要在一个 Java 类中进行调用测试。您可以将这段代码粘贴到一个 Java 类的方法中,然后在该类的 main 方法中调用它进行测试。以下是一个示例代码:
```java
import java.util.Arrays;
import java.util.Map;
import java.util.HashMap;
public class TwoSumTest {
public static void main(String[] args) {
int[] nums = {2, 7, 11, 15};
int target = 9;
int[] result = twoSum(nums, target);
System.out.println(Arrays.toString(result)); // [0, 1]
}
public static int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> hashtable = new HashMap<Integer, Integer>();
for (int i = 0; i < nums.length; ++i) {
if (hashtable.containsKey(target - nums[i])) {
return new int[]{hashtable.get(target - nums[i]), i};
}
hashtable.put(nums[i], i);
}
return new int[0];
}
}
```
在上面示例代码中,我们将两个测试用例写在了 main 方法中,分别使用了不同的数组和目标值。您可以在您的 Java 开发环境中运行这段代码进行测试,看看结果是否符合预期。
public int[] twoSum(int[] nums, int target) { Map<Integer, Integer> hashtable = new HashMap<Integer, Integer>(); for (int i = 0; i < nums.length; ++i) { if (hashtable.containsKey(target - nums[i])) { return new int[]{hashtable.get(target - nums[i]), i}; } hashtable.put(nums[i], i); } return new int[0]; }使用这段代码
这段代码实现了 LeetCode 上题目为 Two Sum 的解法。它的思路是利用哈希表记录数组中的值和对应的下标,然后遍历数组,对于每一个当前值 nums[i],在哈希表中查找是否存在 target - nums[i] 的值,如果存在,则返回这两个值对应的下标。如果不存在,则将当前值及其下标加入哈希表中,以备后续查找。
此算法的时间复杂度为 O(n),空间复杂度为 O(n),其中 n 为数组的长度。