Algorithm Steps
- Given an array of numbers
nums
and atarget
. - For each element at index
i
from0
ton-2
(wheren
is the array length), iterate over every element with indexj
fromi+1
ton
-1. - For each pair
(i, j)
, calculate the sum ofnums[i]
andnums[j]
. - If the sum equals the target, return the indices
[i, j]
.
Solution Program in Different Programming Languages Code
Python
Java
JavaScript
C
C++
C#
Kotlin
Swift
Go
Php
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
for i in range(len(nums) - 1):
for j in range(i + 1, len(nums)):
if nums[i] + nums[j] == target:
return [i, j]