bonfy / algorithm-in-5-minutes

Algorithm in 5 minutes
0 stars 0 forks source link

1. Two Sum #1

Open bonfy opened 5 years ago

bonfy commented 5 years ago

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

Leetcode: Two Sum - https://leetcode.com/problems/two-sum/

bonfy commented 5 years ago

解法1 - 暴力法

两重遍历, 时间复杂度 O(n²)

class Solution:
    def twoSum(self, nums, target):
        L = len(nums)
        for i in range(i, L):
            for j in range(i+1, L):
                if nums[i] + nums[j] == target:
                    return [i, j]
bonfy commented 5 years ago

解法2 - Hash

一重遍历, 时间复杂度 O(n)

class Solution:
    def twoSum(self, nums, target):
        dct = {}
        for num in nums:
            if num in dct:
                return [num, dct[num]]
            else:
                t = target - num
                dct[t] = num
bonfy commented 5 years ago

这里 Leetcode 是假设给定的测试用例肯定有解,严谨点应该在最后加上,表示没有解的情况

    return [-1, -1]