728x90
LeetCode-1
Two Sum : target๊ณผ ์ผ์นํ๋ ๋ฆฌ์คํธ ๋๊ฐ์ ํฉ
note : O
MyAnswer (O(n * n))
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
len_nums = len(nums)
if len_nums==2:
return [0,1]
for i in range(len(nums)):
for j in range(i+1,len(nums)):
if target==(nums[i]+nums[j]):
return [i, j]
Result : 3649ms Memory: 14.9mb
Answer O(n * n) (in์ ์๊ฐ ๋ณต์ก๋ n)
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
for i, n in enumerate(nums):
complement = target - n
if complement in nums[i+1:]:
return [nums.index(n), nums[i+1:].index(complement)+(i+1)] #(i+1) ๋ณด์
Result : 606ms Memory: 15mb
Answer O(n)
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
d = {}
for i, j in enumerate(nums):
r = target - j
if r in d: return [d[r], i]
d[j] = i
# An Upvote will be encouraging
๋ฐ์ํ
'๐ข One step' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[leetcode-15] Three Sum (0) | 2023.03.06 |
---|---|
[leetcode-42] Trapping Rain Water (0) | 2023.03.05 |
[leetcode-5] Longest Palindrome Substring (0) | 2023.03.04 |
[leetcode-49] Group Anagrams (0) | 2023.03.02 |
LeetCode - Time complexity ์๊ฐ ๋ณต์ก๋ (0) | 2023.03.02 |