法一:暴力法
1 class Solution { 2 public int[] twoSum(int[] nums, int target) { 3 // 暴力法 4 for(int i = 0; i < nums.length; i++){ 5 for(int j = i + 1; j < nums.length; j++){ 6 if(nums[i] + nums[j] == target){ 7 return new int[] {i, j}; 8 } 9 } 10 } 11 return null; 12 } 13 }
复杂度分析
时间复杂度为O(n^2),空间复杂度为O(1)
法二:两次HashMap
法三:一次HashMap
思路:
1. 借助一个HashMap<Integer, Integer>, 存储的元素是一个nums[i] 和 i
2. 遍历所有的元素,对于每个元素判断互补的那个元素是否在Map中,如果在根据互补的值作为键取出键值对,返回数组,退出循环
3. 如果不在,则将当前元素和下标作为键值对添加到map中
1 class Solution { 2 public int[] twoSum(int[] nums, int target) { 3 HashMap<Integer, Integer> map = new HashMap<>(); 4 for(int i = 0; i < nums.length; i++){ 5 int another = target - nums[i]; 6 if(map.containsKey(another)){ 7 int j = map.get(another); 8 return new int[] {j, i}; 9 }else{ 10 map.put(nums[i], i); 11 } 12 } 13 return null; 14 } 15 }
原文:https://www.cnblogs.com/hi3254014978/p/12879440.html