[C Language] One question per day (find all the numbers that disappear in the array)

Find all the missing numbers in the array , the link is here.
insert image description here

Let me briefly say here, because I haven’t touched it yet 动态内存,数据结构, so my knowledge is limited, and I did my best 结合题库的评论区to find the one that suits me 解法. I will add various solutions when I have the opportunity in the future.

cycle of violence

The cycle of violence is still the easiest to think of, but the easier it is, the more time-consuming it is, which means it is easier to exceed the time limit.
Ideas:

Double forcycle, 外部控制1~nnumber, 内部遍历numsarray, two by two 比较, 记录the number that does not appear is the number that disappears

Code:

static int arr[99999];//创建数组
int* finddisappearednumbers(int* nums, int numssize, int* returnsize)
{
    
    
    int count = 0;//计数器
    int n = 0;
    for (int j = 1; j <= numssize; j++)
    {
    
    
        count = 0;//每次进入要重置
        for (int i = 0; i < numssize; i++)
        {
    
    
            if (j == nums[i])
            {
    
    
                count++;
                break;
            }
        }
        if (count == 0)//为0说明未出现
            arr[n++] = j;
    }
    *returnsize = n;
    return arr;
}

Sorting + discussion by situation

Ideas:

Sorting is to make the array orderly and operate better.
So what is the matter of discussing according to the situation?
Set it 1~nas a loop variable i, traverse it,
left=0set it as a subscript, and then compare nums[left] with i according to the situation0 from the beginning . At this time , because there will be repeated numbers, for example , at this time, you can use a while loop At that time , it will be put into the result array . : case, so the left in the while will exceed the limit, at this time , we assign the unstarted values ​​in the remaining for loop to the result array in turnleft++

i==nums[left]left++1 2 2 2
i!=nums[left]i

numssizenums[numssize-1]1 2 2 2left==numssizei

Code:

int cmp(int* a, int* b)
{
    
    
    return *a - *b;
}
int* findDisappearedNumbers(int* nums, int numsSize, int* returnSize){
    
    
    qsort(nums,numsSize,sizeof(int),cmp);

    int* res=malloc(sizeof(int) * numsSize);//结果数组,result
    *returnSize=0;
    int left=0;

   for(int i=1;i<=numsSize;i++)
   {
    
    
       if(left<numsSize&&i!=nums[left])//注意:left要放前边,防止短路发生
       {
    
    
           res[(*returnSize)++]=i;
           //*returnsize随着结果数组的增加而增加,
           //最后返回的就是数组大小
       }
       if(left==numsSize)
       {
    
    
           res[(*returnSize)++]=i;
       }
       //while要在最后进行,因为在前边会改变left
       //影响两个if的判断
       while(left<numsSize&&i==nums[left])
       {
    
    
           left++;
       }
   }
    return res;
}

Everyone is welcome to correct errors and discuss.

Guess you like

Origin blog.csdn.net/2301_78636079/article/details/132356650