|
1 | 1 | package in.knowledgegate.dsa.array; |
2 | 2 |
|
3 | | -import java.util.HashMap; |
4 | | -import java.util.Map; |
5 | | - |
6 | 3 | /** |
7 | | - * Given an array of integers nums and an integer target, return indices of the |
8 | | - * two numbers such that they add up to target. You may assume that each input |
9 | | - * would have exactly one solution, and you may not use the same element twice. |
10 | | - * You can return the answer in any order. |
| 4 | + * Given an array of integers nums and an integer |
| 5 | + * target, return indices of the two numbers such |
| 6 | + * that they add up to target. You may assume that |
| 7 | + * each input would have exactly one solution, and |
| 8 | + * you may not use the same element twice. You can |
| 9 | + * return the answer in any order. |
11 | 10 | * <p> |
12 | | - * Example 1: Input: nums = [2,7,11,15], target = 9 Output: [0,1] Explanation: |
13 | | - * Because nums[0] + nums[1] == 9, we return [0, 1]. |
| 11 | + * Example 1: Input: nums = [2,7,11,15], target = |
| 12 | + * 9 Output: [0,1] Explanation: Because nums[0] + |
| 13 | + * nums[1] == 9, we return [0, 1]. |
14 | 14 | * <p> |
15 | | - * Example 2: Input: nums = [3,2,4], target = 6 Output: [1,2] |
| 15 | + * Example 2: Input: nums = [3,2,4], target = 6 |
| 16 | + * Output: [1,2] |
16 | 17 | * <p> |
17 | | - * Example 3: Input: nums = [3,3], target = 6 Output: [0,1] |
| 18 | + * Example 3: Input: nums = [3,3], target = 6 |
| 19 | + * Output: [0,1] |
18 | 20 | * <p> |
19 | 21 | * <p> |
20 | | - * Constraints: 2 <= nums.length <= 104 -109 <= nums[i] <= 109 -109 <= target <= |
21 | | - * 109 Only one valid answer exists. |
| 22 | + * Constraints: 2 <= nums.length <= 104 -109 <= |
| 23 | + * nums[i] <= 109 -109 <= target <= 109 Only one |
| 24 | + * valid answer exists. |
22 | 25 | */ |
23 | 26 | public class TwoSum { |
24 | 27 | public int[] twoSum(int[] nums, int target) { |
25 | | - Map<Integer, Integer> map = new HashMap<>(); |
26 | 28 | for (int i = 0; i < nums.length; i++) { |
27 | | - map.put(nums[i], i); |
28 | | - } |
29 | | - |
30 | | - for (int i = 0; i < nums.length; i++) { |
31 | | - int num = target - nums[i]; |
32 | | - int result = map.getOrDefault(num, -1); |
33 | | - if (result >= 0 && result != i) { |
34 | | - return new int[]{i, result}; |
| 29 | + for (int j = i + 1; j < nums.length; j++) { |
| 30 | + if (nums[i] + nums[j] == target) { |
| 31 | + return new int[] {i , j}; |
| 32 | + } |
35 | 33 | } |
36 | 34 | } |
37 | | - |
38 | | - throw new IllegalArgumentException("invalid input"); |
| 35 | + throw new IllegalArgumentException("Invalid input"); |
39 | 36 | } |
40 | 37 | } |
0 commit comments