-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTwo Sum
More file actions
46 lines (39 loc) · 1.75 KB
/
Two Sum
File metadata and controls
46 lines (39 loc) · 1.75 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
# Brief taken from: 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.
# Example:
# Given nums = [2, 7, 11, 15], target = 9,
# Because nums[0] + nums[1] = 2 + 7 = 9,
# return [0, 1].
# Will use the example values to run
nums = list([2, 7, 11, 15])
target = 9
def slowMethod():
for i in range(0, len(nums)):
for j in range(0, len(nums)):
if i == j:
# Accounts for the two variables being the same value, whilst also allowing for repeating values
continue
elif nums[i] + nums[j] == target:
targetVals = [i, j]
# Without breaks, the code keeps going, thus increasing processing time, as well as the targetVals list will
# be overwritten
break
# Could potentially make the code a function to enable a cleaner exit from the loops
if len(targetVals) == 2:
break
# Checks the end states, could use either the length of the targetVals array, or test for if it exists
if len(targetVals) == 2:
print("The indices of the values that sum to "+str(target)+" are: "+str(targetVals[0])+","+str(targetVals[1]))
else:
print("No matches found")
def hashmapMethod():
# Creates a dictionary with values and their indexes to see if a given value's partner value is in said index.
visited = {}
for i, num in enumerate(nums):
pairVal = target - num
if pairVal not in visited:
visited[num] = i
else:
return [visited[pairVal], i]
print(hashmapMethod())