2341. How many pairs can an array form-data statistics

2341. How many pairs can an array form?

You are given an integer array nums with indexes starting from 0. In one step, you can perform the following steps:

从 nums 选出 两个 相等的 整数
从 nums 中移除这两个整数,形成一个 数对

Please perform this operation on nums multiple times until it cannot continue.

Returns an integer array answer starting from 0 and of length 2 as the answer, where answer[0] is the number of pairs formed and answer[1] is the number of integers remaining after performing as many of the above operations on nums as possible.

Example 1:

Input: nums = [1,3,2,1,3,2,2]
Output: [3,1]
Explanation:
nums[0] and nums[3] form a number pair and are removed from nums, nums = [3,2,3,2,2] .
nums[0] and nums[2] form a number pair and are removed from nums, nums = [2,2,2].
nums[0] and nums[1] form a number pair and are removed from nums, nums = [2].
No more pairs can be formed. A total of 3 number pairs are formed, leaving 1 number in nums.

Example 2:

Input: nums = [1,1]
Output: [1,0]
Explanation: nums[0] and nums[1] form a number pair and are removed from nums, nums = [].
No more pairs can be formed. A total of 1 number pair is formed, leaving 0 numbers in nums.

Example 3:

Input: nums = [0]
Output: [0,1]
Explanation: Unable to form a number pair, there is 1 number left in nums.

This question is relatively simple. The solution code is as follows:



/**
 * Note: The returned array must be malloced, assume caller calls free().
 */
int* numberOfPairs(int* nums, int numsSize, int* returnSize){
    
    
    int count[101];
    int * re=(int *)malloc(sizeof(int)*2);
    *returnSize=2;
    for(int i=0;i<101;i++){
    
    
        count[i]=0;
    }
    re[0]=0;
    re[1]=0;
    for(int i=0;i<numsSize;i++){
    
    
        count[nums[i]]++;
        if(count[nums[i]]==2){
    
    
            re[0]++;
             re[1]--;
             count[nums[i]]=0;
        }
        if(count[nums[i]]==1){
    
    
            re[1]++;
        }
    }
   return re;

}

Guess you like

Origin blog.csdn.net/weixin_43327597/article/details/133268407