My leetcode solution has been (finally!) accepted but I know it can be improved - in particular line 12 and 13.
How can I make this code simpler and more efficient? How can I name elements that are duplicates instead of extracting it from a list?
Q: LeetCode Two Sum
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
You can return the answer in any order.
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
Y = []
for i in nums:
for j in nums:
if i + j == target and i != j:
return([nums.index(i),nums.index(j)])
elif i + j == target and i == j:
for n in nums:
if nums.count(n) > 1:
Y.append(n)
indices = [i for i, val in enumerate(nums) if val == Y[0]]
return indices
I am pretty new at coding and I am not sure how to improve my skills. I have picked up the basics from an intro course but I find leetcode questions super difficult :( I find some hackerrank & codility questions more doable but I am currently hitting a wall as the questions get harder. I copied and pasted the enumerate fn too tbh.
Thanks so much!