Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit df245d6

Browse files
TwoSum
1 parent 7ba618a commit df245d6

File tree

2 files changed

+35
-0
lines changed

2 files changed

+35
-0
lines changed

‎Arrays/001-twosum.py

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
'''Leetcode - https://leetcode.com/problems/two-sum/ '''
2+
'''
3+
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
4+
5+
You may assume that each input would have exactly one solution, and you may not use the same element twice.
6+
7+
You can return the answer in any order.
8+
9+
Input: nums = [2,7,11,15], target = 9
10+
Output: [0,1]
11+
'''
12+
13+
# Solution1
14+
def twoSum(nums, target):
15+
for i in range(len(nums)):
16+
for j in range(i+1, len(nums)):
17+
if nums[i] + nums[j] == target:
18+
return [i, j]
19+
# T:O(N^2)
20+
# S:O(1)
21+
22+
# Solution2
23+
def twoSum(nums, target):
24+
dict = {}
25+
for i in range(len(nums)):
26+
diff = target - nums[i]
27+
if diff in dict:
28+
return [dict[diff], i]
29+
dict[nums[i]] = i
30+
31+
# T: O(N)
32+
# S: O(N)
33+
34+

‎README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ Check the notes for the explaination - [Notes](https://stingy-shallot-4ea.notion
2929
- [x] [Counting Bits](Dynamic-Programming/338-Counting-Bits.py)
3030

3131
- [x] [Arrays](Arrays)
32+
- [x] [Two Sum](Arrays/001-twosum.py)
3233
- [x] [Contains Duplicate](Arrays/217-Contains-duplicate.py)
3334
- [x] [Product Of Array Except Self](Arrays/238-product-of-array-except-self.py)
3435

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /