LEETCODE - Two Sum

Coaspe·2021년 5월 4일
0

Algorithm-배열

목록 보기
2/8
#부르트 포스 방식
def twoSum(self, nums: list[int], target: int) -> list[int]:
    for i in range(len(nums)):
        for j in range(i + 1, len(nums)):
            if nums[i] + nums[j] == target:
                return [i, j]
# 시간 복잡도 O(n^2)

def twoSum2(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)
# in의 시간 복잡도는 O(n)이므로 전체 시간 복잡도는 O(n^2)이지만 in 연산 쪽이 훨씬 더 가볍고 빠르다.
# nums[i + 1:].index(complement) + (i + 1)는 중복된 요소가 있을 수 있어서 사용한 것이다. nums.index(complement)하면 중복된 요소가 있을 때 사용 못 함

def twoSum3(self, nums:list[int], target: int) -> list[int]:
    nums_map = {}

    for i, num in enumerate(nums):
        nums_map[num] = i

    for i, num in enumerate(nums):
        if target - num in nums_map and i != nums_map[target - num]:
            return nums.index(num), nums_map[target - num]

def twoSum4(self, nums:list[int], target: int) -> list[int]:
    nums_map = {}
    # 하나의 for 문으로 통합
    for i, num in enumerate(nums):
        if target - num in nums_map:
            return [nums_map[target-num], i]
        nums_map[num] = i

def twoSum5(self, nums:list[int], target: int) -> list[int]:
    left, right = 0, len(nums) - 1
    while not left == right:
        if nums[left] + nums[right] < target:
            left += 1
        elif nums[left] + nums[right] > target:
            right -= 1
        else:
            return left, right
# 투 포인터

#속도 5 > 4 > 3 > 2 > 1
profile
https://github.com/Coaspe

0개의 댓글