题目:在一个二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
- (void)viewDidLoad {
[super viewDidLoad];
// col
NSArray *array = @[@[@1,@2,@8,@9],//row
@[@2,@4,@9,@12],
@[@4,@7,@10,@13],
@[@6,@8,@11,@15]];
BOOL canFind = [self findNum:8 inArray:array];
BOOL canTfind = [self TfindNum:8 inArray:array];
NSLog(@"last:%d",canFind);
NSLog(@"last:%d",canTfind);
}
- (BOOL)findNum:(int)num inArray:(NSArray *)arr {
NSUInteger totalrow = arr.count;
NSUInteger row = 0;
NSInteger col = ((NSArray *)arr[0]).count - 1;
do {
if ([arr[row][col] intValue] > num) {
if (col > 0) {
col --;
}else {
return NO;
}
}else if ([arr[row][col] intValue] < num){
if (row < (totalrow - 1)) {
row++;
}else {
return NO;
}
}else {
NSLog(@"num%d-行%lu-列%ld",num,(unsigned long)row,(long)col);
return YES;
}
NSLog(@"====%d",[arr[row][col] intValue]);
} while ([arr[row][col] intValue] != num);
return YES;
}
- (BOOL)TfindNum:(int)num inArray:(NSArray *)arr {
NSUInteger totalrow = arr.count;
NSUInteger row = 0;
NSInteger col = ((NSArray *)arr[0]).count - 1;
while (row < totalrow && col > 0) {
if ([arr[row][col] intValue] > num) {
col --;
}else if ([arr[row][col] intValue] < num){
row++;
col = ((NSArray *)arr[0]).count - 1;
}else {
NSLog(@"Tnum%d-行%lu-列%ld",num,(unsigned long)row,(long)col);
return YES;
}
}
return NO;
}
网友评论