1.两数之和
给定一个整数数列,找出其中和为特定值的那两个数。
你可以假设每个输入都只会有一种答案,同样的元素不能被重用。
示例:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
解题思路
第一反应将数组中的数两两相加,找到等于目标值的2个数就是我们要的解。注意数字不能被使用2遍,所以第二层循环要从i+1开始
public int[] twoSum(int[] nums, int target) {
int[] result = new int[2];
for (int i = 0; i < nums.length; i++) {
for (int j = i + 1; j < nums.length; j++) {
if (nums[i] + nums[j] == target) {
result[0] = i;
result[1] = j;
return result;
}
}
}
return result;
}
但是其实如果我们换一个思考问题的方式会有更简便的方法,a+b=c
a = c - b; 在加上文中的提示 数组元素不会重复。所以我们可以使用Map来进行加速。Map的key为数组中的值,map的value为数组下标。当前数组是a时只需要找到key为b的值就好。
public int[] twoSum(int[] nums, int target) {
int[] result = new int[2];
Map<Integer,Integer> map = new HashMap<>(nums.length);
for (int i = 0; i < nums.length; i++) {
int value = target-nums[i];
Integer index = map.get(value);
if (index != null && index != i) {
result[0] = i;
result[1] = index;
break;
}
map.put(nums[i],i);
}
return result;
}
在日常工作中,我们有很多需要用多重循环才能解决的问题都能被Map这种处理方式所替代,以提高程序运行的效率。
LeetCode地址:https://leetcode-cn.com/problems/two-sum/description/
网友评论