【问题标题】:How do I remove doubled items from an array?如何从数组中删除加倍的项目?
【发布时间】:2021-05-14 21:23:58
【问题描述】:

创建从数组中删除双倍项的函数。(将其存储到数组中,该数组可以从主程序访问。使用函数和数组)

例子:

Input: 3 4 4 3 4 1
Output: 4 4 4 1

我编写了一个代码来解决这个问题,但它非常丑陋,老实说我不知道​​如何从数组中删除元素/项目,所以我尝试排序到另一个数组中,我 100%肯定不行。有人知道如何解决此类问题的任何见解吗?如果您对更简洁和更短的代码有任何建议,我会很高兴听到他们的意见。提前非常感谢。 :)

#include<stdio.h>
int doubleElement(int* arr,int *filter,int n);


int main()
{

    int i, n;

    printf("Enter no of elements."); //first prompt
    scanf("%d", &n);

    int arr[n];
    int filter[n]; 

    printf("\nEnter Elements:");   
    
    for(i=0;i<n;i++)
    {
        scanf("%d", &arr[i]);
    }

    doubleElement(arr, filter, n); // Pass into double function

    printf("\nOutput:");
    for(i=0;i<n;i++)
    {
        printf("%d ", filter[i]);
    }
}

int doubleElement(int* arr, int* filter, int n)
{
    int i, j, k=0, count, counter;

    int move=0;
    for(i=0;i<n;i++) // First Loop
    {
        count=1; //Frequency tracker, set to 1 because of base.
        for(j=i+1;j<n;j++) //2nd Loop
        {
            if(arr[i]==arr[j])
            {
                count++;
            }
        }
        if(count==1||count>1) //if statement for non doubled items
        {

            for(k=counter;k<count;k++) // We want to repeat the value contained by arr[i] until we meet count and sort the non doubled item.
            {
                filter[k]=arr[i];
            }
            counter=k;
            move++; //Increment for filter array, everytime there is a successful non doubled item
        }
    }
}

【问题讨论】:

  • 你能对数组进行排序吗?然后很容易找到连续的重复项并仅将第一个副本复制到目标数组。
  • 您有重复的问题。这里参考:stackoverflow.com/questions/9613960/…
  • 我可以尝试对数组进行排序,然后通过一个循环来检查频率,但是如何只复制等于 1 个频率或大于 1 个频率的重复项?
  • 看看 Example InputOutput - 这不是所谓的 duplicate question i> 是关于。

标签: c duplicates


【解决方案1】:

这不是很有效,但很简单,并且具有按要求工作的优点:

    for (i = 0; i < n; )
    {   int j, k = arr[i], move, count;
        for (count = j = 0; j < n; ++j) count += arr[j] == k;   // count items equal to k
        if (count == 2)
        {   // doubled (occurring exactly twice) - move elements above index i to the left
            for (move = j = i; move < n; ++move) if (arr[move] != k) arr[j++] = arr[move];
            n = j;  // adjust number of elements
        }
        else ++i;
    }

【讨论】:

    猜你喜欢
    • 2021-10-19
    • 2021-10-03
    • 2017-11-26
    • 2016-09-07
    • 1970-01-01
    • 2016-10-30
    • 2021-08-15
    相关资源
    最近更新 更多