【问题标题】:how to remove duplicates from the array如何从数组中删除重复项
【发布时间】:2022-01-03 06:40:59
【问题描述】:

我有多个数组,我需要返回客户输入的订单的值,这些数组有重复的值,所以即使在下订单时将它们从低到高排序后,他也会获取重复的值。如何删除重复的? 前任。 int testA1[] = { 25000, 20000, 29499, 10000, 20000, 29000, 25000, 20000 , 25000 , 10000 }; int order1 = 3;

#include<stdio.h>

int lowestPrice(int array[], int size, int order){
    int tempArray[size];
    
    for (size_t i = 0; i < size; i++)
        tempArray[i] = array[i];

    for (size_t i = 0; i < size; i++)
        for (size_t j = i; j < size; j++)
            if (tempArray[j] < tempArray[i]) {
                int tmp = tempArray[i];
                tempArray[i] = tempArray[j];
                tempArray[j] = tmp;
            }

    int j = 0;
    for (size_t i = 0; i < size -1; i++){
        if(tempArray[i] != tempArray[i+1])
        {
            tempArray[j] = tempArray[i];                
            j++;    
        } 
        tempArray[j] = tempArray[i-1];
    }   
       
    if(order > size || order < 0){
        return -1;
    }
    else{
        return tempArray[order];    
    }
}

【问题讨论】:

  • 你应该看看stackoverflow中的类似问题(如果你学习如何适应其他人的解决方案来解决你的问题,这对你来说会更好),这里有一个例子stackoverflow.com/questions/28757237/…
  • 排序去除重复后数组为10000, 20000, 25000, 29000, 29499,所以array[3]为29000。
  • 谢谢!!我来看看他们
  • 排序并删除重复项后,它将是 10000、20000、25000、29000、29499,但我需要先删除重复项,否则它仍然是 25000
  • 问题说你期望结果是25000。但是order=3 的正确结果是29000

标签: arrays c


【解决方案1】:
main(void){
int testA1[] = { 25000, 20000, 29499, 10000, 20000, 29000, 25000, 20000 , 25000 , 10000 };
int size = sizeof(testA1) / sizeof(int); //size of array
// if your orders are only going to be positive numbers as it should for your wealth :
// (change duplicate value by -1)
for (int i = 0; i < size ; ++i)
{
    int is_duplicate = testA1[i];
    if (is_duplicate == -1)
        continue ;
    int j = i +1;
    while ( j < size) {
        if (is_duplicate == testA1[j])
            testA1[j] = -1;
        ++j;
    }
}
// sort it ;) :
    for (size_t i = 0; i < size; i++)
        for (size_t j = i; j < size; j++)
            if (testA1[j] < testA1[i]) {
                int tmp = testA1[i];
                testA1[i] = testA1[j];
                testA1[j] = tmp;
            }
    int new_index = 0;
    while (testA1[new_index] == -1)
        ++new_index;
// here is for you to see the new state (you can remove this part)
    for (int i = new_index; i < size; ++i)
        printf("%d\n", testA1[i]);
// now get your order price from the new index (index + your_desired_value) 
    return testA1[new_index + -->your_desired_value<--];
}

【讨论】:

    猜你喜欢
    • 2017-06-21
    • 2012-10-04
    • 2014-06-07
    • 2010-09-05
    • 1970-01-01
    • 1970-01-01
    • 2011-06-29
    相关资源
    最近更新 更多