LeetCode Brushing Notes (Python3) - 1. The sum of two numbers (difficulty: easy) (2021-05-09)

Starting today, write at least one question every day on average, and record your own gains.

LeetCode Algorithm Questions - Question 1: The sum of two numbers
(click to view the title)
(click to view the official solution)

Two solutions:

# 解法1:暴力求解法 -> 时间复杂度:O(N^2) 空间复杂度:O(1)
class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        N = len(nums)
        for i in range(0, N):
            for j in range(i + 1, N):
                if nums[i] + nums[j] == target:
                    return [i, j]
        return []
# 解法2:哈希表法 -> 时间复杂度:O(N) 空间复杂度:O(N)
class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        hashtable = dict() # 定义哈希表,即字典
        for i, num in enumerate(nums):
            if target - num in hashtable:
                return [hashtable[target - num], i]
            hashtable[nums[i]] = i # 定义哈希表(字典)中的一个键对
        return []

The topic itself is simple. The point is to understand the basic mechanism of LeetCode through this question, and learn a few small knowledge points by the way.

1. How to give the results required by the system

The output result required by LeetCode can be directly returned in the official given function. For example, the following is the basic code attached to the official question. Just return the desired result after this function.

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:

2. Don't be too obsessed with reducing the execution time of your own code

Under the premise of not changing the programming language type, the lower the computational complexity of the algorithm, the shorter the execution time is generally. But pay attention, don't be too persistent, and the one who is lower will be lower than him when he sees it is useful. As far as this topic is concerned, looking at other people's results (Python, not Python3), the best only takes 4ms; but the same code takes 20ms on my computer. Therefore, the time given by LeetCode varies with the performance of the computer. As long as the algorithm achieves the minimum computational complexity, there is no need to dwell on this; proper reference is sufficient.

Tips: In the column of submission records after personal code submission, the top line on the left is
"execution results: By displaying details >"
At this point, click display details, you can see the execution time distribution chart and execution time of all submitters of this topic Consumption memory distribution chart. Click the blue column in the chart to see the sample code corresponding to the execution time or memory consumed by execution.

3. How to use the hash table

The dictionary in Python3 uses a hash table structure. For specific usage, refer to Solution 2 above. In the follow-up, it is necessary to understand the implementation method of the hash table in detail, which needs to be supplemented.

4. How to use the enumerate function

# for 循环使用 enumerate
seq = ['one', 'two', 'three']
for i, element in enumerate(seq):
	print i, element
# results:
# 0 one
# 1 two
# 2 three

5. The solution to the "List" error that specifies the data type of the formal parameter

When programming, the "List" of the formal parameter data type specified in the function may report an error "Unresolved reference 'List'" (unresolved reference "List"). At this point, just add the following code at the beginning of the program.

from typing import List

6. Tips for speeding up the range function

range(N)
range(0, N) # 这种用法速度更快

The latter of the above two methods is faster. In this question, using the second line of code is 4ms faster than using the first line of code.

Guess you like

Origin blog.csdn.net/AbaloneVH/article/details/116568983