add: 数据流中第一个唯一的数字
This commit is contained in:
23
src/array/first-unique-number-in-data-stream.js
Normal file
23
src/array/first-unique-number-in-data-stream.js
Normal file
@ -0,0 +1,23 @@
|
||||
/**
|
||||
* @param nums: a continuous stream of numbers
|
||||
* @param number: a number
|
||||
* @return: returns the first unique number
|
||||
*/
|
||||
export const firstUniqueNumber = function (nums, number) {
|
||||
const due = new Set()
|
||||
const queue = new Set()
|
||||
for (const n of nums) {
|
||||
if (queue.has(n)) {
|
||||
queue.delete(n)
|
||||
due.add(n)
|
||||
} else if (!due.has(n)) {
|
||||
queue.add(n)
|
||||
}
|
||||
|
||||
if (n === number) break
|
||||
}
|
||||
|
||||
if (!due.has(number) && !queue.has(number)) return -1
|
||||
|
||||
return Array.from(queue)[0] || -1
|
||||
}
|
Reference in New Issue
Block a user