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) +})