I'm attempting the first problem on leetcode and my code passes the first 19 tests but fails due to a time exceeded failure on the last test. This is what I have so far:
class Solution:
def twoSum(self, nums, target):
k = 0
n = len(nums)-1
temp = []
for x in range(k,n):
for y in range(k+1,n+1):
if (nums[x]+nums[y] == target) and (x < y):
temp.append(x)
temp.append(y)
break
return temp
Please let me know if you have any information that you think could potentially help me. For those of you unfamiliar with the two sums problem. Here it is:
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]
I'm asking about the specifics about how to optimize MY code, not have other people write the code for me. Afterall, memorizing code won't do me any good if I don't know how to do it myself with my own thought processes. I'm asking for advice.