Skip to content

Commit b1848b8

Browse files
committed
leetcode 167
1 parent 403151c commit b1848b8

File tree

4 files changed

+37
-2
lines changed

4 files changed

+37
-2
lines changed

README.md

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,10 +6,11 @@
66

77
## leetcode
88

9-
- 1. Two Sum `easy` `array` [link](https://leetcode.com/problems/two-sum/description/) [code](./leetcode_1_two_sum_easy_array.js)
9+
- 1. Two Sum `easy` `array` [link](https://leetcode.com/problems/two-sum/description/) [code](./leetcode_1.js)
10+
- 1. Two Sum II `easy` `array` [link](https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/description/) [code](./leetcode_167.js)
1011

1112
## lintcode
1213

13-
- 407. Plus One `easy` `string` [link](https://lintcode.com/problem/plus-one/description) [code](./lintcode_407_plus_one_easy_string.js)
14+
- 407. Plus One `easy` `string` [link](https://lintcode.com/problem/plus-one/description) [code](./lintcode_407.js)
1415

1516

File renamed without changes.

leetcode_167.js

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
/*
2+
Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number.
3+
4+
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2.
5+
6+
Note:
7+
8+
Your returned answers (both index1 and index2) are not zero-based.
9+
You may assume that each input would have exactly one solution and you may not use the same element twice.
10+
11+
Example:
12+
13+
Input: numbers = [2,7,11,15], target = 9
14+
Output: [1,2]
15+
Explanation: The sum of 2 and 7 is 9. Therefore index1 = 1, index2 = 2.
16+
*/
17+
18+
/**
19+
* @param {number[]} numbers
20+
* @param {number} target
21+
* @return {number[]}
22+
*/
23+
var twoSum = function(numbers, target) {
24+
let indices;
25+
const map = new Map;
26+
numbers.map((n, i) => {
27+
const complement = target - n;
28+
if (map.has(complement)) indices = [map.get(complement) + 1, i + 1];
29+
map.set(n, i);
30+
});
31+
return indices;
32+
};
33+
34+
console.log(twoSum([2, 7, 11, 15], 9));
File renamed without changes.

0 commit comments

Comments
 (0)