LeetCode-探索-初级算法-数组-9. 两数之和(个人做题记录,不是习题讲解)
-
语言:java
-
思路:两层遍历,寻找两数和等于target的下标
-
代码(32ms):
class Solution { public int[] twoSum(int[] nums, int target) { int len = nums.length; int[] res = new int[2]; for(int i = 0;i<len-1;++i){ for(int j = i+1;j<len;++j){ if(nums[i]+nums[j] == target){ res[0] = i; res[1] = j; return res; } } } return null; } }
-
参考代码1(2ms):利用map记录遍历过的数字,然后如果包含当前数字和过去记录数字之和为target就返回数组。
class Solution { public int[] twoSum(int[] nums, int target) { HashMap<Integer, Integer> my_map=new HashMap<>(); for(int i=0;i<nums.length;i++){ int complement = target-nums[i]; if(my_map.containsKey(complement)){ return new int[] {i, my_map.get(complement)}; } my_map.put(nums[i],i); } throw new IllegalArgumentException("No two sum solution"); } }
-
参考代码2(3ms):
class Solution { public int[] twoSum(int[] nums, int target) { if(nums == null || nums.length < 2){ return new int[]{-1,-1}; } int[] res = new int[]{-1,-1}; HashMap<Integer,Integer> map = new HashMap<Integer, Integer>(); for (int i = 0; i < nums.length ; i++){ if (map.containsKey(target - nums[i])){ res[0] = map.get(target - nums[i]); res[1] = i; return res; } map.put(nums[i],i); } return res; } }
-
参考后重写(3ms):
class Solution { public int[] twoSum(int[] nums, int target) { int len = nums.length; int[] res = new int[2]; int tmp = 0; Map<Integer,Integer> map = new HashMap<Integer,Integer>(); for(int i = 0;i < len;++i){ tmp = target - nums[i]; if(map.containsKey(tmp)){ return new int[]{map.get(tmp),i}; } map.put(nums[i],i); } return null; } }