728x90
leetcode.com/problems/two-sum/
Two Sum - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
풀이
from typing import *
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
for i in range(len(nums)):
j = i+1
while j < len(nums):
if nums[i] + nums[j] == target:
returnlist = [i,j]
returnlist.sort()
return returnlist
j += 1
in range(시작숫자, 종료숫자, step)
시작숫자와 step은 생략이 가능함.
그래서 그런지 이전까지 in range(숫자)형태만 봐와서 시작숫자에 대한 조건을 걸 수 있는지 몰랐다.
enumerate
순서가 있는 자료형(list,set,tuple 등)을 익덱스를 포함한 enumerate 객체로 리턴함.
참고 : wikidocs.net/16045
위키독스
온라인 책을 제작 공유하는 플랫폼 서비스
wikidocs.net
처음 생각했던 알고리즘의 문제점(틀린이유)
newnums = []
for i in nums:
if i < target:
newnums.append(i)
print(newnums)
for i in range(len(newnums)):
for j in range(len(newnums)-1):
j += 1
print(i,j)
if newnums[i] + newnums[j] == target:
print(newnums[i]+newnums[j])
returnlist = [i,j]
returnlist.sort()
return returnlist
- newnums를 하면 순서가 달라짐여기서 원하는 것은 정답이 되는 "숫자"가 아닌 "index" 즉 순서이기 때문에 newnums를 하면 정답 또함 달라짐.
- 이중 for문에 집착함.
j는 무조건 i보다 뒤에서 시작해야하는데, 이중 for문에 집착해서 해결법을 찾는데 오래 걸림
in range 문에서 시작하는 숫자를 정해주면 됨. - for i in range보다 for i in newnums를 쓰고 싶었음.
728x90
'study > LeetCode' 카테고리의 다른 글
[Python] 561. Array Partition I (0) | 2021.02.17 |
---|---|
[Python] 15. Two Sum (0) | 2021.02.17 |
[Python] 819. Most Common Word (0) | 2021.01.15 |
[Python] 937. Reorder Log Files (0) | 2021.01.15 |
[Python] 344. Reverse String (0) | 2021.01.08 |