Topic describes

Given an array of integers and a target value, find two numbers that neutralize the target value in the array.

You can assume that there is only one answer for each input and that the same elements cannot be reused.

Example:

Given nums = [2, 7, 11, 15], target = 9

Because nums[0] + NUMs [1] = 2 + 7 = 9

So return [0, 1]

Train of thought

Idea 1:

violence

Idea 2:

[I] [I] [I] [I] [I] [I] [I] [I] [I] [I] The time complexity of this method is O(N), the space complexity is O(N), using space in exchange for time.

Code implementation

package Array; import java.util.Arrays; import java.util.HashMap; Given an array of integers and a target value, find two numbers that neutralize the target value in the array. * You can assume that there is only one answer for each input and that the same elements cannot be reused. */ public class Solution1 { public static void main(String[] args) { Solution1 solution1 = new Solution1(); int[] nums = {2, 7, 11, 15}; int target = 9; int[] result = solution1.twoSum(nums, target); System.out.println(Arrays.toString(result)); } /** * use HashMap to store array elements and index mappings. If target-nums [I] is present in the HashMap, then target-nums [I] is present in the HashMap. * This method has a time complexity of O(N) and a space complexity of O(N), using space in exchange for time. * * @param nums * @param target * @return */ public int[] twoSum_2(int[] nums, int target) { HashMap<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}; } else { map.put(nums[i], i); } } return null; } /** * violence, Public int[] twoSum(int[] nums, int target) {for (int I = 0;  i < nums.length; i++) { for (int j = i + 1; j < nums.length; j++) { if (nums[i] + nums[j] == target) { return new int[]{i, j}; } } } return null; }}Copy the code


Wu Peixuan



www.cnblogs.com/wupeixuan/