Given an array, without using extra space, move all zeros to the end and no-zeros to the beginning. The function should return the number of non-zeros.
Anonymous
-(int)sortZerosAndReturnCountOfThem:(NSMutableArray *)arr { NSLog(@"before: %@", arr); int cursorFromStart = 0; int cursorFromEnd = (int)arr.count - 1; while (cursorFromStart < cursorFromEnd) { while (arr[cursorFromStart].intValue != 0) { cursorFromStart++; } while (arr[cursorFromEnd].intValue == 0) { cursorFromEnd--; } if (cursorFromStart < cursorFromEnd) { arr[cursorFromStart] = arr[cursorFromEnd]; arr[cursorFromEnd] = @(0); } } NSLog(@"after: %@", arr); int counter = 0; for (NSNumber *num in arr) { if (num.intValue == 0) { counter++; } } NSLog(@"counter: %d", counter); return counter; }
Check out your Company Bowl for anonymous work chats.