题目:
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。
示例:

代码:
- 解法一
class Solution {
public int[] twoSum(int[] nums, int target) {
//数组为空
if (nums == null) {
throw new IllegalArgumentException("This array is empty");
}
//遍历数组 寻找符合的结果
for (int i = 0; i < nums.length; i++) {
for (int j = i+1; j < nums.length; j++) {
if (nums[j]+nums[i]==target) {
return new int[]{i,j};
}
}
}
return null;
}
}
- 别人的代码
使用哈希算法
class Solution {
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};
} else {
map.put(nums[i], i);
}
}
return null;
}
}
博客提出在给定整数数组 nums 和目标值 target 的情况下,找出数组中和为目标值的两个整数并返回其下标,且不能重复利用数组中同样元素,还给出示例及使用哈希算法的解法代码。
689

被折叠的 条评论
为什么被折叠?



