Offer arrives, dig friends to pick up! I am participating in the 2022 Spring Recruitment Check-In Event, click to view the event details .
1. Problem description
You are given an array of integers nums
, which contains 2 * n
integers.
You need to nums
divide into n
pairs, satisfying:
- Each element belongs to only one pair.
- Elements in the same pair are equal .
If it can be nums
divided into n
pairs, please return true
, otherwise return false
.
Topic link: Divide an array into pairs of equal numbers .
Second, the subject requirements
Sample
输入: nums = [3,2,3,2,2,2]
输出: true
解释:
nums 中总共有 6 个元素,所以它们应该被划分成 6 / 2 = 3 个数对。
nums 可以划分成 (2, 2) ,(3, 3) 和 (2, 2) ,满足所有要求。
复制代码
visit
1.简单模拟判断、位运算
2.建议用时10~35min
复制代码
3. Problem Analysis
1. Simulation
There are many ways to do this question. At first, I sorted the array from small to large, and then the two are judged as a group.
Don't judge the end of the loop, as long as the two arrays of a group are not equal, just return false.
2. Bit operations
If you don't understand the relevant knowledge points of bit operation, you can read this article, which explains in more detail:
Algorithm questions are practiced daily --- Day 45: Bit operations .
Bit operation can XOR two identical numbers to 0, then we XOR the array from the beginning to the end, if the output is 0, then the condition is met.
But this method has a bug, that is, the result of XOR of unequal numbers may be 0, so the second-to-last example is difficult.
Fourth, the encoding implementation
class Solution {
public:
bool divideArray(vector<int>& nums) {
int i,n=nums.size();
sort(nums.begin(),nums.end());//排序
for(i=0;i<n-1;i+=2)//两两一组
{
if(nums[i]!=nums[i+1])//不相等
return false;//返回错误
}
return true;//返回正确
}
};
复制代码