iOS算法两道解题思路

121 阅读2分钟

废话不多说开整

第一题:

数列前2项为 1 1,从第3项开始,若为奇数项,则值为前两项之和,若为偶数项,则值为前两项之和的2倍 可知该数列前6项为 1 1 2 6 8 28 求该数列的第n项 请用递归和循环两种方式实现

这个问题第一感觉就是个递归先用递归试试

/// 求第N项 递归实现
- (NSInteger)fineFutureNumberValueWithindex:(NSInteger)ns {
  
    NSInteger resultValue = 0;
    if (ns <=0) {// 不处理
        return resultValue;
    }else if (ns == 1 || ns == 2)  {
        return 1;
    }else if (ns%2 == 0) { // 偶数
        resultValue = ([self fineFutureNumberValueWithindex:ns - 1] + [self fineFutureNumberValueWithindex:ns - 2]) * 2;
    }else if (ns%2 == 1){ // 奇数
        resultValue = ([self fineFutureNumberValueWithindex:ns - 1] + [self fineFutureNumberValueWithindex:ns - 2]);
    }
    return resultValue;

}

这里要求使用递归和循环两种实现 递归好实现 循环感觉没啥思路 想了大半天

/// 求第N项 For循环实现
- (void)lookForFutuerValueWithIndex:(NSInteger)ns {

    NSMutableArray *array = @[].mutableCopy;
    NSInteger resultValue = 0;
    for (int i = 0; i <= ns; i ++) {
        if (i == 0) {
            [array addObject:@"0"];
        }else if (i == 1 || i == 2) {
            resultValue = 1;
            [array addObject:@"1"];
        }else if (i%2 == 0){ // 偶数项
            resultValue = ([array[i - 1] integerValue] + [array[i - 2] integerValue]) * 2;
            [array addObject:[NSString stringWithFormat:@"%ld",resultValue]];
        }else if (i%2 == 1) { // 奇数项
            resultValue = [array[i - 1] integerValue] + [array[i - 2] integerValue];
            [array addObject:[NSString stringWithFormat:@"%ld",resultValue]];
        }
    }
    resultValue = [array.lastObject integerValue];
    DLog(@"数组第N项的值是 ====%ld ",resultValue);

}

最后大概就是这样了 没有验证太大的数 前边几个都对上了 如果有为欢迎指正

接着看第二题

给定一个int型数组,找出其中大于0的数字中倒数第二小的数字的下标 例如 1 -1 3 2 0,其中大于0的数字有1 3 2,倒数第二小的数字为2,其下标为3

这个相对容易一些了就 直接贴代码了就


- (void)lookForSecMaxValue {

    NSArray *intArr = @[@(1),@(-1),@(3),@(2),@(0)];
    __block NSInteger maxValue = 0;
    __block NSInteger secMax = [intArr.firstObject integerValue];
    __block NSInteger sec_index = 0;
    [intArr enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSInteger nowValue = [obj integerValue];
        if (nowValue > maxValue) {
            maxValue = nowValue;
        }
        if (nowValue > secMax && nowValue < maxValue) {
            secMax = nowValue;
            sec_index = idx;
        }
    }];
    DLog(@"倒数第二大的数是:%ld 下标为===%ld ",secMax,sec_index);

}

一开始看到是算法的面试题感觉很恐惧 因为之前也没有深入的专门学习过 但是对着题目冷静一想感觉这些也都是项目中都会用到的一些逻辑计算,所以慢慢来吧别慌。

写在最后: 2024新的一年开始了 送给那些在找工作路上的小伙伴希望大家都能找到自己称心的工作吧 !路虽远行则将至 加油吧!!!