算法题两则

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

/**
*递归
*/

-(NSInteger)counts:(NSInteger)index{
    if(index == 1 || index == 2){
        return 1;
    }else if (index%2 == 0){
        return ([self counts:index-2] + [self counts:index-1])*2;
    }else if (index%2 == 1){
        return ([self counts:index-2] + [self counts:index-1]);
    }else{
        return 0;//输入0或者负数返回0
    }
}

/**
*for 循环
*/

-(NSInteger)numCounts:(NSInteger)index{
    NSMutableArray *array = @[].mutableCopy;
    
    for (int i = 1; i <= index; i++) {
        if(i == 1 || i == 2){
            [array addObject:1];
        }else if (index%2 == 0){
            NSInteger temp = (array[index-2] + array[index-1])*2;
            [array addObject:temp]
        }else if (index%2 == 1){
            NSInteger temp = (array[index-2] + array[index-1]);
            [array addObject:temp]
        }
    }
    return array.lastObject;
}

第二题:
给定一个int型数组,找出其中大于0的数字中倒数第二小的数字的下标
例如 1 -1 3 2 0,其中大于0的数字有1 3 2,倒数第二小的数字为2,其下标为3
尽量不使用排序

/**
*遍历保存最大值和第二大值
*/

-(NSString* )numCounts:(NSArray *)array{
    
    NSInteger temp_max = 0; //最大数
    NSInteger temp_max2 = 0;//第二大数
    NSInteger index_max = 0;//最大数下标
    NSInteger index_max2 = 0;//第二大数下标
    
    for (int i = 0; i < array.count; i++) {
        NSInteger obj = array[i];
        if (i==0) {
            index_max = i;
            index_max2 =i;
            temp_max = obj;
            temp_max2 =obj;
        }else{
            if (obj > temp_max) {
                temp_max = obj;
                index_max = i;

            }else if (obj > temp_max2){
                temp_max2 =obj;
                index_max2 =i;
            }
        }
    }
    
    if (temp_max2 <= 0) {
        return "倒数第二大值小于等于0,不满足题义";
    }
    
    return [NSString stringWithFormat:@"倒数第二大值为%d,下标为%d",temp_max2,index_max2];
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容