Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dautermann/4f82dfdf920afbd20fbc to your computer and use it in GitHub Desktop.
Save dautermann/4f82dfdf920afbd20fbc to your computer and use it in GitHub Desktop.
an algorithm question from a recent interview: given an array (for example, [ 1, 0, 2, 0, 0, 3, 4 ]), implement a method that: 1. returns the number of non-zero elements (4) 2. moves the non-zero elements to the beginning of the array (the rest of the elements don't matter) -> both [ 1, 2, 3, 4, 0, 0, 0] and [ 4, 1, 3, 2, X, Y, Z ] are valid
/*
Given an array (for example, [ 1, 0, 2, 0, 0, 3, 4 ]), implement a method that
1. returns the number of non-zero elements (4)
2. moves the non-zero elements to the beginning of the array (the rest of the elements don't matter)
-> both [ 1, 2, 3, 4, 0, 0, 0] and [ 4, 1, 3, 2, X, Y, Z ] are valid
*/
@interface FB : NSObject
@end
@implementation FB
- (NSInteger) countAndRearrangeNonZeroElementsFromThisArray: (NSMutableArray *) originalArray
{
NSInteger countOfZeros = 0;
NSInteger indexOfLastNonZeroItem = [originalArray count] - 1;
for(NSInteger index = 0; index < [originalArray count]; index++)
{
NSNumber * numberFromArray = [originalArray objectAtIndex:index];
if([numberFromArray intValue] == 0)
{
countOfZeros++;
[originalArray exchangeObjectAtIndex:indexOfLastNonZeroItem withObjectAtIndex:index];
indexOfLastNonZeroItem--;
}
if(index > indexOfLastNonZeroItem)
break;
}
return(countOfZeros);
}
@end
int main (int argc, const char * argv[])
{
@autoreleasepool {
FB * fbObj = [[FB alloc] init];
if(fbObj)
{
NSMutableArray *mutableArray = [@[@1, @0, @2, @0, @0, @3, @4 ] mutableCopy];
NSInteger numberOfZeros = [fbObj countAndRearrangeNonZeroElementsFromThisArray:mutableArray];
NSLog(@"numberOfZeros = %ld %@", numberOfZeros, mutableArray);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment