数位重组

来源:互联网 发布:沙钢收购大数据公司 编辑:程序博客网 时间:2024/04/28 07:47

问题:给定两个数组表示的整数,比如x=1234={1,2,3,4},y=2410={2,4,1,0},返回第一个整数的重组后的值最接近第二个整数,并且大于第二个整数。假设两个数组的大小相同,并且肯定能找到渡河条件的数。输入{1,2,3,4}和{2,4,1,0}返回{2,4,1,3}

OC算法实现:

////  GetClosestBigger.h//  Algorithm////  Created by han shuai on 2016/9/25.//  Copyright © 2016年 han shuai. All rights reserved.///** 10 */#import <Foundation/Foundation.h>@interface GetClosestBigger : NSObject- (NSArray *)getClosestBigger:(NSArray *)x y:(NSArray *)y;@end

////  GetClosestBigger.m//  Algorithm////  Created by han shuai on 2016/9/25.//  Copyright © 2016年 han shuai. All rights reserved.//#import "GetClosestBigger.h"@implementation GetClosestBigger- (NSArray *)getClosestBigger:(NSArray *)x y:(NSArray *)y{    NSMutableArray *res = [NSMutableArray array];        //对x升序    x = [x sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {        NSNumber *num1 = (NSNumber *)obj1;        NSNumber *num2 = (NSNumber *)obj2;        if (num1.intValue > num2.intValue) {            return NSOrderedDescending;        }        else if(num1.intValue < num2.intValue)        {            return NSOrderedAscending;        }        else        {            return NSOrderedSame;        }    }];        int index = 0;//扫描x    NSMutableArray *used = [NSMutableArray array];//记录x数字是否使用    for (int i = 0; i < x.count; i++) {        [used addObject:[NSNumber numberWithBool:NO]];    }        for (int i = 0; i < x.count; i++) {        index = 0;//每次从x开头扫描        //x的值已经被使用 或者 x的值比y的当前值小,index扫描到x的下一位        while (index < x.count && ([used[index] boolValue] || x[index] < y[i])) {            index++;        }                [res addObject:x[index]];//找到目标        used[index] = [NSNumber numberWithBool:YES];//记录此值已被使用                //大于情况 复制未使用的递增序列        if (x[index] > y[i]) {            for (int j = 0; j < x.count; j++) {                if (![used[j] boolValue]) {                    [res addObject:x[j]];                }            }            break;        }            }    return res;}@end


0 0
原创粉丝点击