Issue
I have this problem:
Given an array of integers
nums
and an integertarget
, return the indices of two numbers that add up totarget
.
Example 1:
Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Output: Because nums[0] + nums[1] == 9, we return [0, 1].
With the code below was able to get the values added in array using set
and Map
What I need help is to return the indices
const arr = [{key1: 2}, {key1: 7}, {key1: 11}, {key1: 15}];
const k = 9;
const valueSet = new Set(arr.flatMap((x) => Object.values(x)));
const valueArray = [...valueSet];
valueArray.forEach((v1, i1) => {
for (let i2 = i1 + 1; i2 < valueArray.length; i2++) {
if ((v1 + valueArray[i2]) === k) {
// Return the indices
return valueArray[i2];
}
}
});
Solution
You have to parse and find the combination of indexes which gives you the sum.
Below code will help you
const arr = [{ key1: 2 }, { key1: 7 }, { key1: 11 }, { key1: 15 }];
const k = 9;
let valueSet = new Set(arr.flatMap((x) => Object.values(x)));
let valueArray = [...valueSet];
let indices;
let isFound = false;
// valueArray.forEach((v1, i1) => {
for (let i1 = 0; i1 < valueArray.length && !isFound; i1++) {
for (let i2 = i1 + 1; i2 < valueArray.length && !isFound; i2++) {
if ((valueArray[i1] + valueArray[i2]) === k) {
//Return the Indices
indices = [i1, i2];
isFound = true;;
}
}
}
console.log(indices);
Answered By - Nitheesh
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.