[LeetCode] Two sum
- 문제링크
https://leetcode.com/problems/two-sum/
- Code
남에게 권하지 않는 방법이다...
내가 엄청 길게 풀었다.
class Solution(object):
def twoSum(self, nums, target):
dic = {}
result=[]
#Input key value { nums' index : nums' data}
for i, numIndex in enumerate(nums):
dic[i]=numIndex
#make list
listValues= list(dic.values())
listKeys = list(dic.keys())
for i, numIndex in enumerate(nums):
num1 = target-numIndex #value
num2 = target-num1 #value
if num1 in dic.values() and num2 in dic.values():
if(num1==num2):
if(listValues.count(num1) >1):
pos1 = listValues.index(num1)
dic[pos1]=-1
listValues= list(dic.values()) #value update
pos2 = listValues.index(num2)
else:
continue
else: #num1 != num2
pos1 =listValues.index(num1)
pos2 = listValues.index(num2)
if listKeys[pos1]> listKeys[pos2]: #if result is [2,1] -> [1,2]
result = [listKeys[pos2], listKeys[pos1]]
break
else:
result = [listKeys[pos1], listKeys[pos2]]
break
return result
- Time
'공부 > Algorithm' 카테고리의 다른 글
[프로그래머스] 햄버거 만들기 (0) | 2023.05.05 |
---|---|
[LeetCode] Implement Trie (0) | 2022.03.21 |
[HackerRank] Balanced Brackets (0) | 2022.03.11 |
[HackerRank] Jesse and Cookies (0) | 2022.03.09 |
[HackerRank] Equal stacks (0) | 2022.03.08 |
댓글