- 两数之和
给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 的那 两个 整数,并返回它们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。
你可以按任意顺序返回答案。
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> hashmap = new HashMap<>();
for (int i=0; i<nums.length ;i++){
int complement = target - nums[i];
if(hashmap.containsKey(complement))
return new int[]{hashmap.get(complement), i};
hashmap.put(nums[i], i);
}
throw new IllegalArgumentException("No two sum solution");
}
本文介绍了一种解决两数之和问题的有效算法。通过使用哈希表,可以在O(n)的时间复杂度内找到数组中和为目标值的两个整数的下标。这种方法避免了传统双层循环的低效性。
2万+

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



