add: 数据流中第一个唯一的数字

This commit is contained in:
yi-ge 2020-05-14 18:03:49 +08:00
parent 8f84fc8c66
commit 9c2a165583
3 changed files with 35 additions and 1 deletions

View File

@ -86,7 +86,7 @@ LeetCode 与 LintCode 解题记录。此为个人练习仓库,代码中对重
- LeetCode 13. 罗马数字转整数 <https://leetcode-cn.com/problems/roman-to-integer/>
- LintCode 419. 罗马数字转整数 <https://www.lintcode.com/problem/roman-to-integer/description>
## 数组
## 数组/队列/集合/映射
- [电话号码的字母组合](src/array/letter-combinations-of-a-phone-number.js)
@ -283,6 +283,10 @@ LeetCode 与 LintCode 解题记录。此为个人练习仓库,代码中对重
- LeetCode 221. 最大正方形 <https://leetcode-cn.com/problems/maximal-square/>
- LintCode 436. 最大正方形 <https://www.lintcode.com/problem/maximal-square/description>
- [数据流中第一个唯一的数字](src/array/first-unique-number-in-data-stream.js)
- LintCode 685. 数据流中第一个唯一的数字 <https://www.lintcode.com/problem/first-unique-number-in-data-stream/description>
## 栈
- [最大矩阵](src/stack/maximal-rectangle.js)

View 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
}

View File

@ -0,0 +1,7 @@
import { firstUniqueNumber } from '../../src/array/first-unique-number-in-data-stream'
test('数据流中第一个唯一的数字', () => {
expect(firstUniqueNumber([1, 2, 2, 1, 3, 4, 4, 5, 6], 5)).toBe(3)
expect(firstUniqueNumber([1, 2, 2, 1, 3, 4, 4, 5, 6], 7)).toBe(-1)
expect(firstUniqueNumber([1, 2, 2, 1, 3, 4], 3)).toBe(3)
})