给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
以下是我自己用双循环写的,时间复杂度O(n^2)。
/*双循环*/
class Solution {
public int[] twoSum(int[] nums, int target) {
int i=0;
for(int j=0;j<nums.length-1;j++){
for(int k=j+1;k<nums.length;k++){
if(nums[j]+nums[k]==target){
int[] arr ={j,k};
return arr;
}
}
}
throw new IllegalArgumentException("No two sum solution"); //没有结果抛出异常,不加会报错“no return statement”
}
}
IllegalArgumentException此异常表明向方法传递了一个不合法或不正确的参数。
下面是我看到的答案里的最优代码,原理是
用哈希表查询时间复杂度为o(1),查询不到则将值存入哈希表。其中用到了containsKey方法判断键值是否存在,return new int[] {i,j}可直接返回一个数组。
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
for(int i = 0; i< nums.length; i++) {
if(map.containsKey(target - nums[i])) {
return new int[] {map.get(target-nums[i]),i};
}
map.put(nums[i], i);
}
throw new IllegalArgumentException("No two sum solution");
}
}
/*作者:guanpengchn
链接:https://leetcode-cn.com/problems/two-sum/solution/jie-suan-fa-1-liang-shu-zhi-he-by-guanpengchn/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。*/