Skip to content

Commit 09c57bc

Browse files
committed
170
1 parent 08a877c commit 09c57bc

File tree

4 files changed

+74
-0
lines changed

4 files changed

+74
-0
lines changed

167_two_sum_ii/problem.txt

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
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.
2+
3+
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. Please note that your returned answers (both index1 and index2) are not zero-based.
4+
5+
You may assume that each input would have exactly one solution.
6+
7+
Input: numbers={2, 7, 11, 15}, target=9
8+
Output: index1=1, index2=2

167_two_sum_ii/two_sum_ii.py

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
class Solution(object):
2+
def twoSum(self, numbers, target):
3+
"""
4+
:type numbers: List[int]
5+
:type target: int
6+
:rtype: List[int]
7+
"""
8+
if len(numbers)<2:return []
9+
start = 0
10+
end = len(numbers)-1
11+
12+
while True:
13+
n = numbers[start]+numbers[end]
14+
if n==target:
15+
return [start+1, end+1]
16+
elif n<target:
17+
start+=1
18+
else:
19+
end-=1
20+
if start==end:
21+
return []
22+

170_two_sum_iii/problem.txt

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
Design and implement a TwoSum class. It should support the following operations: add and find.
2+
3+
add - Add the number to an internal data structure.
4+
find - Find if there exists any pair of numbers which sum is equal to the value.
5+
6+
For example,
7+
add(1); add(3); add(5);
8+
find(4) -> true
9+
find(7) -> false

170_two_sum_iii/two_sum_iii.py

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
from collections import defaultdict
2+
class TwoSum(object):
3+
4+
def __init__(self):
5+
"""
6+
initialize your data structure here
7+
"""
8+
self.numbers = defaultdict(int)
9+
10+
def add(self, number):
11+
"""
12+
Add the number to an internal data structure.
13+
:rtype: nothing
14+
"""
15+
self.numbers[number]+=1
16+
17+
def find(self, value):
18+
"""
19+
Find if there exists any pair of numbers which sum is equal to the value.
20+
:type value: int
21+
:rtype: bool
22+
"""
23+
for n in self.numbers:
24+
m = value-n
25+
if m!=n and m in self.numbers:
26+
return True
27+
if m==n and self.numbers[n]>1:
28+
return True
29+
return False
30+
31+
32+
# Your TwoSum object will be instantiated and called as such:
33+
# twoSum = TwoSum()
34+
# twoSum.add(number)
35+
# twoSum.find(value)

0 commit comments

Comments
 (0)