简体   繁体   English

如何从数组中删除重复项

[英]how to remove duplicates from the array

I have multiple arrays and I need to return the value of the order the customer enters, the arrays have duplicated values so even after sorting them from low to high when the order is placed he'll take the duplicated value.我有多个 arrays 并且我需要返回客户输入的订单的值,arrays 有重复的值,所以即使在下订单时将它们从低到高排序后,他也会采用重复的值。 how can I remove the duplicated?如何删除重复的? ex.前任。 int testA1[] = { 25000, 20000, 29499, 10000, 20000, 29000, 25000, 20000, 25000, 10000 }; int testA1[] = { 25000, 20000, 29499, 10000, 20000, 29000, 25000, 20000, 25000, 10000 }; int order1 = 3; int order1 = 3; <-- it should print out 29000but instead it prints 25000 <-- 它应该打印出 29000 但它打印出 25000

#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];    
    }
}
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<--];
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM