File tree Expand file tree Collapse file tree 1 file changed +8
-16
lines changed Expand file tree Collapse file tree 1 file changed +8
-16
lines changed Original file line number Diff line number Diff line change 1
1
class Solution {
2
2
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 ]++;
18
6
}
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 ;
20
12
}
21
13
}
You can’t perform that action at this time.
0 commit comments