-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathalgoW3D2.js
More file actions
52 lines (40 loc) · 1.13 KB
/
algoW3D2.js
File metadata and controls
52 lines (40 loc) · 1.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
/* https://leetcode.com/problems/two-sum/
Given an array of integers, return indices of the
two numbers such that they add up to a specific target.
You may assume that each input would have EXACTLY ONE SOLUTION,
and you may not use the same element twice.
the array is unsorted, contains no floats, and there may be duplicate values
Given arr = [2, 11, 7, 15], target = 9,
Because arr[0] + arr[2] = 2 + 7 = 9
return [0, 2].
example 1
0 1 2 3
given: [2, 11, 7, 15]
target: 9
output: [0,2]
example 2
0 1 2
given: [3,2,4]
target: 6
output: [1,2]
example 3
given: [3,3]
target: 6
output: [0,1]
*/
function twoSum(arr, target) {
//Your code here
for (var i = 0; i<arr.length; i++) {
for (var j = i+1; j<arr.length; j++) {
var sum = arr[i] + arr[j]
if (sum == target) {
return [i, j]
}
}
}
}
// -------------------------------------------------
console.log(twoSum([2, 11, 7, 15], 9)); // [0,2]
console.log(twoSum([3, 2, 4], 6)); // [1,2]
console.log(twoSum([3, 3], 6)); // [0,1]
// if you finish early -- can you do this without nesting for loops?