Skip to content

Commit 70bead3

Browse files
authored
Update Number of Students Unable to Eat Lunch.java
1 parent 34ffbcc commit 70bead3

File tree

1 file changed

+8
-16
lines changed

1 file changed

+8
-16
lines changed
Lines changed: 8 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,13 @@
11
class Solution {
22
public int countStudents(int[] students, int[] sandwiches) {
3-
int studentIdx = 0;
4-
int sandwichIdx = 0;
5-
Map<Integer, Integer> studentState = new HashMap<>();
6-
while (sandwichIdx < sandwiches.length) {
7-
if (sandwiches[sandwichIdx] == students[studentIdx]) {
8-
sandwichIdx++;
9-
students[studentIdx] = -1;
10-
} else if (students[studentIdx] != -1) {
11-
// Check to see if we have finished one complete iteration without consuming any sandwich
12-
if (studentState.containsKey(studentIdx) && studentState.get(studentIdx) == sandwichIdx) {
13-
break;
14-
}
15-
studentState.put(studentIdx, sandwichIdx);
16-
}
17-
studentIdx = studentIdx == students.length - 1 ? 0 : studentIdx + 1;
3+
int[] preferenceCount = new int[2];
4+
for (int preference : students) {
5+
preferenceCount[preference]++;
186
}
19-
return sandwichIdx == sandwiches.length ? 0 : sandwiches.length - sandwichIdx;
7+
int i = 0;
8+
for (i = 0; i < sandwiches.length && preferenceCount[sandwiches[i]] > 0; i++) {
9+
preferenceCount[sandwiches[i]]--;
10+
}
11+
return sandwiches.length - i;
2012
}
2113
}

0 commit comments

Comments
 (0)