Two Sum Indices
Given an array of integers nums and an integer target, return the indices of two numbers such that they add up to target.
You may assume each input has exactly one solution, and you may not use the same element twice.
The hash table strategy is to scan once, store each number with its index, and check whether target - current already exists.
Example 1:
Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Example 2:
Input: nums = [3,2,4], target = 6
Output: [1,2]
Example 3:
Input: nums = [3,3], target = 6
Output: [0,1]
Algorithm Flow

Recommendation Algorithm Flow for Two Sum Indices - Budibadu
Best Answers
java
import java.util.*;
class Solution {
public int[] two_sum_indices(int[] nums, int target) {
Map<Integer, Integer> seen = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
int need = target - nums[i];
if (seen.containsKey(need)) return new int[]{seen.get(need), i};
seen.put(nums[i], i);
}
return new int[]{};
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this problem.
