Skip to content

Commit 681f038

Browse files
committed
feat: solve No.1942
1 parent 615280b commit 681f038

File tree

1 file changed

+51
-2
lines changed

1 file changed

+51
-2
lines changed

1901-2000/1942. The Number of the Smallest Unoccupied Chair.md

Lines changed: 51 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -71,7 +71,56 @@ Since friend 0 sat on chair 2, we return 2.
7171
## Solution
7272

7373
```javascript
74-
74+
/**
75+
* @param {number[][]} times
76+
* @param {number} targetFriend
77+
* @return {number}
78+
*/
79+
var smallestChair = function(times, targetFriend) {
80+
var emptyChairs = new Set();
81+
var max = -1;
82+
var list = times.reduce((arr, item, i) => {
83+
arr.push({ i, type: 1, time: item[0] });
84+
arr.push({ i, type: 2, time: item[1] });
85+
return arr;
86+
}, []).sort((a, b) => {
87+
// be careful if someone's arrival time equals the other's leave time
88+
// make sure we process leave one first
89+
if (a.time === b.time) {
90+
return b.type - a.type;
91+
}
92+
return a.time - b.time;
93+
});
94+
var map = {};
95+
for (var i = 0; i < list.length; i++) {
96+
var item = list[i];
97+
if (item.type === 1) {
98+
// someone arrival
99+
if (emptyChairs.size) {
100+
// found empty chair someone left before
101+
map[item.i] = findMin(emptyChairs);
102+
emptyChairs.delete(map[item.i]);
103+
} else {
104+
// go to the last chair
105+
map[item.i] = max + 1;
106+
max = map[item.i];
107+
}
108+
if (item.i === targetFriend) {
109+
break;
110+
}
111+
} else {
112+
// someone leave
113+
emptyChairs.add(map[item.i]);
114+
}
115+
}
116+
return map[targetFriend];
117+
};
118+
119+
// should replace set with min heap
120+
// so that time complexity could be O(nlog(n))
121+
var findMin = function(list) {
122+
return Array.from(list).sort((a, b) => a - b)[0];
123+
};
75124
```
76125

77126
**Explain:**
@@ -80,5 +129,5 @@ nope.
80129

81130
**Complexity:**
82131

83-
* Time complexity : O(n).
132+
* Time complexity : O(n^2).
84133
* Space complexity : O(n).

0 commit comments

Comments
 (0)