Two questions a day T36

Two questions a day T36

algorithm

LeetCode T Interview Question 56-I. Number of occurrences of numbers in the array [1]

description

An array of integers numsin addition to the two figures, other figures appear twice. Please write a program to find these two numbers that only appear once. The required time complexity is O(n), and the space complexity is O(1).

Example 1:

Input: nums = [4,1,4,6]
Output: [1,6] or [6,1]

Example 2:

Input: nums = [1,2,10,4,1,4,3,3]
Output: [2,10] or [10,2]

limit:

2 <= nums <= 10000

analysis

The hash table to solve this problem is very simple, see the code.

Code

var singleNumbers = function(nums) {
var obj = {}
nums.forEach(count => {
    let attr = count + ""
    obj[attr]? delete obj[attr] :(obj[attr] = 1)
})
return Object.keys(obj)
};

front end

The difference between browser and Node event loop

Browser

The execution sequence of microtasks and macrotasks in the browser is as follows:

• Execute a task (macro task) • After executing the micro-task queue (micro task)

This cycle goes on and on

The execution order of tasks (macro tasks) of the browser is in html#event-loops[2]. Common tasks (macro tasks) are not translated, such as: setTimeout, setInterval, script (overall code), I/O operations, UI rendering, etc. Common micro-tasks such as: new Promise().then (callback), MutationObserver (html5 new feature), etc.

Node

Node's event loop is implemented by libuv, quote a picture from the official website:

The general task (macro task) execution sequence is as follows:

• Timers: execute the scheduled setTimeout() and setInterval() callback functions at this stage. •Pending callbacks: I/O callbacks that are delayed until the next loop iteration are executed. • idle, prepare: Only used internally by the system. • Polling: Retrieve new I/O events; execute I/O-related callbacks (in almost all cases, except for closed callback functions, which are scheduled by timers and setImmediate()), the rest The node will block here. •Check detection: the setImmediate() callback function is executed here. •Close callbacks Closed callback functions: some callback functions to be closed, such as socket.on('close', ...).

The execution sequence of micro tasks and macro tasks in Node

Before Node 10:

•Perform all tasks of a stage•Perform the content in the nextTick queue•Then perform the content of the microtask queue

After Node 11: The behavior of the browser is unified, and the micro task queue is executed every time a macro task is executed.

References

[1]Interview Question 56-I. The number of times the number appears in the array: https://leetcode-cn.com/problems/shu-zu-zhong-shu-zi-chu-xian-de-ci-shu-lcof/ [2] html#event -loops: https://html.spec.whatwg.org/multipage/webappapis.html#event-loops

Reference: https://cloud.tencent.com/developer/article/1664379 Two questions a day T36-Cloud + Community-Tencent Cloud