From 9c2a165583f33da4612c00d0235dd70c2e93a4bf Mon Sep 17 00:00:00 2001 From: yi-ge Date: Thu, 14 May 2020 18:03:49 +0800 Subject: [PATCH] =?UTF-8?q?add:=20=E6=95=B0=E6=8D=AE=E6=B5=81=E4=B8=AD?= =?UTF-8?q?=E7=AC=AC=E4=B8=80=E4=B8=AA=E5=94=AF=E4=B8=80=E7=9A=84=E6=95=B0?= =?UTF-8?q?=E5=AD=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 6 ++++- .../first-unique-number-in-data-stream.js | 23 +++++++++++++++++++ ...first-unique-number-in-data-stream.test.js | 7 ++++++ 3 files changed, 35 insertions(+), 1 deletion(-) create mode 100644 src/array/first-unique-number-in-data-stream.js create mode 100644 test/array/first-unique-number-in-data-stream.test.js diff --git a/README.md b/README.md index 1f8c7e5..8514e55 100644 --- a/README.md +++ b/README.md @@ -86,7 +86,7 @@ LeetCode 与 LintCode 解题记录。此为个人练习仓库,代码中对重 - LeetCode 13. 罗马数字转整数 - LintCode 419. 罗马数字转整数 -## 数组 +## 数组/队列/集合/映射 - [电话号码的字母组合](src/array/letter-combinations-of-a-phone-number.js) @@ -283,6 +283,10 @@ LeetCode 与 LintCode 解题记录。此为个人练习仓库,代码中对重 - LeetCode 221. 最大正方形 - LintCode 436. 最大正方形 +- [数据流中第一个唯一的数字](src/array/first-unique-number-in-data-stream.js) + + - LintCode 685. 数据流中第一个唯一的数字 + ## 栈 - [最大矩阵](src/stack/maximal-rectangle.js) diff --git a/src/array/first-unique-number-in-data-stream.js b/src/array/first-unique-number-in-data-stream.js new file mode 100644 index 0000000..7e508d3 --- /dev/null +++ b/src/array/first-unique-number-in-data-stream.js @@ -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 +} diff --git a/test/array/first-unique-number-in-data-stream.test.js b/test/array/first-unique-number-in-data-stream.test.js new file mode 100644 index 0000000..5f093f0 --- /dev/null +++ b/test/array/first-unique-number-in-data-stream.test.js @@ -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) +})