classSolution{ publicint[] twoSum(int[] nums, int target) { Map<Integer, Integer> map = new HashMap<>(); for (int i = 0; i < nums.length; i++) { map.put(nums[i], i); } for (int i = 0; i < nums.length; i++) { int complement = target - nums[i]; if (map.containsKey(complement) && map.get(complement) != i) { returnnewint[] { i, map.get(complement) }; } } thrownew IllegalArgumentException("No two sum solution"); } }
classSolution{ publicint[] twoSum(int[] nums, int target) { Map<Integer, Integer> map = new HashMap<>(); for (int i = 0; i < nums.length; i++) { int complement = target - nums[i]; if (map.containsKey(complement)) { returnnewint[] { map.get(complement), i }; } map.put(nums[i], i); } thrownew IllegalArgumentException("No two sum solution"); } }
复杂度分析:
时间复杂度:O(n), 我们只遍历了包含有 n 个元素的列表一次。在表中进行的每次查找只花费 O(1)的时间。