[leetcode question writing day 1] Enumeration method

Topic 1. Sum of two numbers

Given an integer array nums and an integer target value target, please find the two integers in the array whose sum is the target value target and return their array subscripts.

You can assume that each input will correspond to only one answer. However, the same element in the array cannot appear repeatedly in the answer.

You can return answers in any order.

Example 1:

Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Explanation: Because nums[0] + nums[1] == 9, return [0, 1].

parse

  • Normal practice Enumerate via a double loop. The first-level loop enumerates each value num in the array, and the second-level loop determines whether each value is equal to target - num.
  • Optimization Use a hash table. The goal in the second level loop is to find whether there is a value equal to target - num. The optimization method is to use a hash table, which can reduce the complexity from O(n) to O(1). Using a hash table to look up is to create a hash table (dictionary), with num as the key and the subscript as the value. If target - num exists in the dictionary (target - num in hashtable), you can directly return the corresponding subscript hash [target - num]

Question 2 204. Counting prime numbers - LeetCode

Given an integer n, return the number of all prime numbers less than a non-negative integer n.
Example 1:
Input: n = 10
Output: 4
Explanation: Less than There are 4 prime numbers of 10, they are 2, 3, 5, and 7.

parse

  • General Determine whether a number is prime: there are no factors from 2 to sqrt(n) (that is, it is divisible by it)
  • General practice Traverse all numbers less than a non-negative integer n, determine whether they are prime numbers, and add up the number of prime numbers. The time complexity is O(nsqrt(n)
  • Sieve of Ehrstein If a number x is a prime number, then 2x, 3x, 4x…xx, x(x+1) are not prime numbers. Therefore, when judging that a number x is a prime number, you can filter out all the multiples of x. None of them are prime numbers. -> Optimize to filter out xx, x(x+1), x*(x+2)..., because 2x, 3x, 4x have been filtered by 2, 3, 4.

Summary of common grammar mistakes

  1. range(i,j) is left closed and right open
  2. You must add math.sqrt() before using sqrt(), which returns a floating point number. isqrt() returns an integer not greater than sqrt()
  3. Define an array of length n, initialized to 0: list = [0] *n
  4. Determine whether a value is in the dictionary: x in hashtable
  5. Define a set: my_set = set(). To add elements to the set, use .add(x). The set can be deduplicated.
  6. x raised to the nth power: x**n (not x^n)

Guess you like

Origin blog.csdn.net/a61022706/article/details/134939671