Pergunta de entrevista da empresa Booking.com

Given an array of integers and integer K, return another array holding integers appeared K times in the given array

Respostas da entrevista

Sigiloso

29 de out. de 2016

NSArray *array = [self getElementsFromArray:@[@1, @3, @3, @1, @2, @3, @4, @1, @2] whereElementCountIsGreaterThan:1]; - (NSArray *)getElementsFromArray:(NSArray *)allElements whereElementCountIsGreaterThan:(NSInteger)frequency { NSCountedSet *countedSet = [NSCountedSet setWithArray:allElements]; NSMutableArray *finalElements = [[NSMutableArray alloc] init]; for (NSNumber *item in countedSet) { if ([countedSet countForObject:item] > frequency) { [finalElements addObject:item]; } } return finalElements; }

1

Sigiloso

14 de nov. de 2016

- (NSArray *)findElements:(NSArray*)array withK:(int)kTimes { NSMutableArray *resultArray = [NSMutableArray array]; NSMutableDictionary *dict = [NSMutableDictionary dictionary]; for (NSNumber *number in array) { if ([dict objectForKey:number.stringValue]) { NSInteger count = [[dict objectForKey:number.stringValue] integerValue]; [dict setValue:[NSNumber numberWithInteger:count+1] forKey:number.stringValue]; } else { [dict setValue:[NSNumber numberWithInteger:1] forKey:number.stringValue]; } } for (NSString *key in dict) { NSInteger count = [[dict objectForKey:key] integerValue]; if (count == kTimes) { [resultArray addObject:key]; } } return resultArray; }

Sigiloso

23 de nov. de 2020

func solution(_ nums: [Int], _ k: Int) -> [Int] { var dict = [Int: Int]() for num in nums { dict[num, default: 0] += 1 } return Array(dict.filter { $0.value == k }.map {$0.key}) }