I felt like doing an algorithm and found this problem on leetcode
Given an array of integers, find two numbers such that they add up to a specific target num
O(nlogn)
time complexity.O(n)
time.O(n)
time.Overall complexity is O(nlogn)
.
Implementation in python:
class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
p = nums[:]
p.sort() #sorting in -> O(nlogn)
r = len(nums)-1
l =0
#find the indices -> O(n)
for i in range(len(nums)):
if(p[l] + p[r]<target):
l += 1
elif (p[l] + p[r]>target):
r -=1
else :
first_num = p[l]
second_num = p[r]
#find the indices of the numbers -> O(n)
for i in range(len(nums)):
if(nums[i]==first_num):
first_index = i
elif (nums[i]==second_num):
second_index = i
return [first_index,second_index]
One line solution in python :
class Solution(object):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
def twoSum(self, nums, target):
x = [[i, nums.index(target-j)] for i,j in enumerate(nums) if nums.count(target-j) > 0 and nums.index(target-j)!=i]
return x.pop()
Here is an O(n):
public int[] findSumMatched(int[] numbers, int target) {
Map<Integer, Integer> mapOfNumbers = new HashMap<Integer, Integer>();
for (int i = 0; i<numbers.length; i++) {
int secondNumber = target - numbers[i];
if (mapOfNumbers.get(secondNumber) != null){
return new int[] {mapOfNumbers.get(secondNumber), i};
}
mapOfNumbers.put(numbers[i], i);
}
throw new IllegalArgumentException();
}
Just curious, but what's wrong with this O(n) solution?
public int[] twoSum(int[] nums, int target) {
for (int i = 0; i < nums.length - 1; i++){
if (nums[i] + nums[i+1] == target)
return new int[] {i, i+1};
}
return null;
}