给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 target 的那 两个 整数,并返回它们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。
你可以按任意顺序返回答案。
我的代码
class Solution {
public int[] twoSum(int[] nums, int target) {
int sum = 0;
int[] rt = new int[2];
for (int i = 0; i < nums.length - 1; i++) {
for (int j = i + 1; j < nums.length; j++) {
sum = nums[i] + nums[j];
if (target == sum) {
rt[0]=i;
rt[1]=j;
return rt;
}
}
}
return rt;
}
}
属于是O(n2)的暴力解法。但是代码不够简洁。官方暴力解法
class Solution {
public int[] twoSum(int[] nums, int target) {
int n = nums.length;
for (int i = 0; i < n; ++i) {
for (int j = i + 1; j < n; ++j) {
if (nums[i] + nums[j] == target) {
return new int[]{i, j};
}
}
}
return new int[0];
}
}
作者:力扣官方题解
链接:https://leetcode.cn/problems/two-sum/solutions/434597/liang-shu-zhi-he-by-leetcode-solution/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
其中可以优化之处
1.主要就是数组的定义和赋值。直接 return new int[]{i, j};看起来简洁一些,如果没有解return new int[0];就相当于一个空的数组也不用占两个int的空间。
关于优化解法
就是用HashMap的containsKey方法,可以只用一层循环。在循环中直接判断为了凑成target,除了当前这个这个nums[i]还差什么数字。也是在同一层循环中,一次一次的将当前的数字和位置凑成HashMap的键值对。在判断时如果在map中有,就是之前存过的,如果没有就继续向后看。比如说位置2和位置8的数字能凑成target,虽然在i=2时,去找发现需要凑的数HashMap中还没有,但是当遍历到位置8时,又能反过来发现位置2的能凑成target,所以不会遗漏,也不需要单独循环一次给hashMap初始化。
class 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];
}
}
作者:力扣官方题解
链接:https://leetcode.cn/problems/two-sum/solutions/434597/liang-shu-zhi-he-by-leetcode-solution/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。