How I solve a simple problem, as a developer

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]

‘Where do we go from here?’ - Thanh Bui

1. First thing first, understand the problem

2. Break the problem into smaller problems:

if (a + b) == target
print(a, b)

nums = [2, 7, 11, 15]
target = 9

3. Fill knowledge gap to achieve main objective:

for (index1, num1) in enumerate (nums):
for (index2, num2) in enumerate(nums):
# skip condition
if (index1 == index2):
continue
if (num1 + num2 == target):
print(index1, index2)

4. Try to make it work better:

for (index1, num1) in enumerate(nums):
for (index2, num2) in enumerate(nums):
# skip condition
if (index1 >= index2):
continue
if (num1 + num2 == target):
print(index1, index2)
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
for (index1, num1) in enumerate(nums):
for (index2, num2) in enumerate(nums):
# skip condition
if (index1 >= index2):
continue
if (num1 + num2 == target):
return[index1, index2]

# The end.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Phạm Huy Phát

Phạm Huy Phát

Người Việt Nam sống trên Internet là chủ yếu