Table of contents
Open Table of contents
The Problem
Given an array of integers nums
and an integer target
, return indices of the two numbers such that they add up to target
.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
You can return the answer in any order.
Example 1 | Example 2 | Example 3 |
---|---|---|
Input: nums = [2,7,11,15], target = 9Output: [0,1] Explanation: Because nums[0] + nums[1] == 9, we return [0, 1]. | Input: nums = [3,2,4], target = 6Output: [1,2] Explanation: Because nums[1] + nums[2] == 6, we return [1, 2]. | Input: nums = [3,3], target = 6Output: [0,1] Explanation: Because nums[0] + nums[1] == 6, we return [0, 1] |
The Approach
The goal is to find the very first pair’s indices that add up to target
. Using a nested for-loop, we can loop across nums
& every other element for each index of nums
.
By getting the desiredNumber = target - currentNumber
, we can check if this number is present in the other indices of nums
. If this number is found, the valid pair is found & returned.
My Solution
class Solution {
int[] pair = new int[2];
public int[] twoSum(int[] nums, int target) {
// First loop gets the current number & the desired value to reach target.
for (int i = 0; i < nums.length; i++) {
int currentNumber = nums[i];
int desiredNumber = target - currentNumber;
// Checks remaining elements to locate desired value if present.
for (int j = i + 1; j < nums.length; j++) {
if (nums[j] == desiredNumber) {
pair[0] = i;
pair[1] = j;
return pair;
}
}
}
return pair;
}
}
The first for-loop loops over all the elements in nums
. The desiredNumber is then calculated.
The nested loop then loops over the elements from i + 1
(as the same element cannot be used twice), checking if the current index’s element is equal to desiredNumber
. When it is found, the pair’s indices are returned.