给定一个已排序的整数数组,如何找到最长的相同值的数字序列,并将该数字存储在指针变量中?

问题描述 投票:0回答:1

我想编写一个 C 函数,它获取一个已排序的整数数组、其大小和一个整数指针作为参数,并完成以下任务: 1. 查找并返回数组中相同值的最长数字序列的长度排序数组,以及 2. 将该序列中的数字存储在作为参数给出的指针所指向的变量中。

这是我的尝试,但没有产生预期的结果,我不知道为什么。 请建议我如何修复我的代码,以便它执行所需的任务。

int MaxSequence(const int arr[], int size, int* number)
{
    int i = 0;
    int max = 1;
    int curr_max = 1;
    *number = arr[i];
    
    for(i = 0; i < size - 1; i++) {
        if(arr[i] == arr[i+1]) {
            curr_max++;            
        }
        else if (curr_max > max) {
            max = curr_max;
            curr_max = 0;
            *number = arr[i];
            }               
    }

    return max;
}
c pointers
1个回答
0
投票
int MaxSequence(const int arr[], int size, int* number)
{
    int i = 0;
    int max = 1;
    int curr_max = 1;
    *number = arr[i];
    
    for(i = 0; i < size - 1; i++) {
        if(arr[i] == arr[i+1]) {
            curr_max++;            
        }
        else if (curr_max > max) {
            max = curr_max;
            curr_max = 0;
            *number = arr[i];
        } else{
            curr_max = 0
        }              
    }

    return max;
}

当 curr_max > max 时,您正在更新 curr_max,但我们需要在数字变化时始终更新它,并且仅当 curr_max 大于当前最大值时才更新 max。

添加了一个 else 条件,该条件将在 curr_max 时运行 <= max and we do not need to update the max value and number pointer (Considering there will be only 1 number occurring max times)

© www.soinside.com 2019 - 2024. All rights reserved.