You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C语言如何对数组去重并按输入顺位返回对应值

数组排序去重按顺位取值实现方案

现有代码问题梳理

你的需求是先将数组从小到大排序、去重后,按用户输入的顺位返回对应数值,现有代码的错误集中在两处:

  • 去重逻辑错误:tempArray[j] = tempArray[i-1]; 放在了if判断外,每次循环都会错误覆盖j位置的有效数值,且循环结束后没有补充最后一个唯一值,导致去重后数组内容完全异常
  • 索引与边界判断错误:去重后的数组长度远小于原数组size,用原size判断order越界会出错;另外你示例中的顺位是从1开始计数,对应数组0下标需要减1,原代码直接返回tempArray[order]索引对应错了

修复后可运行代码

#include<stdio.h>

int lowestPrice(int array[], int size, int order){
    // 入参先做基础校验
    if(size <= 0 || order <= 0) return -1;
    int tempArray[size];
    
    // 拷贝原数组避免修改原数据
    for (int i = 0; i < size; i++)
        tempArray[i] = array[i];

    // 冒泡排序从小到大
    for (int i = 0; i < size; i++)
        for (int j = i; j < size; j++)
            if (tempArray[j] < tempArray[i]) {
                int tmp = tempArray[i];
                tempArray[i] = tempArray[j];
                tempArray[j] = tmp;
            }

    // 去重逻辑
    int unique_len = 0;
    for (int i = 0; i < size; i++){
        // 只保留和上一个值不一样的元素
        if(i == 0 || tempArray[i] != tempArray[i-1]){
            tempArray[unique_len] = tempArray[i];
            unique_len++;
        }
    }

    // 校验order是否超出去重后数组的长度
    if(order > unique_len){
        return -1;
    }
    // 顺位从1开始,转0下标返回
    return tempArray[order - 1];    
}

// 测试用例
int main() {
    int testA1[] = { 25000, 20000, 29499, 10000, 20000, 29000, 25000, 20000 , 25000 , 10000 };
    int size = sizeof(testA1)/sizeof(testA1[0]);
    int order1 = 3;
    printf("%d", lowestPrice(testA1, size, order1)); // 输出29000符合预期
    return 0;
}

效果验证

你提供的测试数组排序后结果为:[10000,10000,20000,20000,20000,25000,25000,25000,29000,29499],去重后得到长度为5的新数组:[10000,20000,25000,29000,29499],顺位3对应索引2的数值为29000,和预期一致。

内容的提问来源于stack exchange,提问作者kan3

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 10:24:05