二维数组搜索

来源:互联网 发布:我的世界1.7.10java 编辑:程序博客网 时间:2024/06/04 23:30

问题:设计一个算法对m*n矩阵进行搜索,这个矩阵拥有如下属性。

1、每行的数都是从左到右排序好的;

2、每行的数大于上行的数。


思路:二维数组展开为一维数组,用二分查找法查找。

NSArray模拟矩阵:

        NSArray *line0 = [NSArrayarrayWithObjects:@1,@2,@3,@4,nil];

        NSArray *line1 = [NSArrayarrayWithObjects:@5,@6,@7,@8,nil];

        NSArray *line2 = [NSArrayarrayWithObjects:@9,@10,@11,@12,nil];

        NSArray *a = [NSArrayarrayWithObjects:line0,line1,line2,nil];


OC算法实现:


////  SearchMatrix.h//  Algorithm////  Created by han shuai on 2016/9/27.//  Copyright © 2016年 han shuai. All rights reserved.///** 21 */#import <Foundation/Foundation.h>@interface SearchMatrix : NSObject- (NSArray *)searchMatrix:(NSArray *)a target:(int)target;@end

////  SearchMatrix.m//  Algorithm////  Created by han shuai on 2016/9/27.//  Copyright © 2016年 han shuai. All rights reserved.//#import "SearchMatrix.h"@implementation SearchMatrix- (NSArray *)searchMatrix:(NSArray *)a target:(int)target{    NSInteger m = a.count;//矩阵行    NSInteger n = [[a firstObject] count];//矩阵列        NSInteger i = 0;//矩阵展开的头部    NSInteger j = m*n-1;//矩阵展开的尾部        while (i<=j) {        NSInteger mid = (i+j)/2;                int value = [[a[mid/n] objectAtIndex:mid%n] intValue];//中值        if (target == value) {            return @[[NSNumber numberWithInt:(int)mid/n],[NSNumber numberWithInt:(int)mid%n]];        }        else if (target > value)        {            i = mid+1;        }        else        {            j = mid-1;        }    }        return @[];}@end


0 0
原创粉丝点击