Last active
September 9, 2015 12:35
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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