Given an array of numbers nums, in which exactly two elements appear only once and all
the other elements appear exactly twice. Find the two elements that appear only once.
For example:
Given nums = [1, 2, 1, 3, 2, 5], return [3,
5].
Note:
- The order of the result is not important. So in the above example,
[5, 3]is also correct. - Your algorithm should run in linear runtime complexity. Could you implement it using only constant space complexity?
输入一组整数,找出其中只出现一次的数,其余数都出现两次。
本题和136题(http://blog.youkuaiyun.com/hiroshiten/article/details/72637489)的区别在于,136题有且只有一个单独的数,本题可以有零个到多个。
思路:将数组排序,然后比较相邻的两个数是否相同。注意只有两个数且两个数不相同的情况。
vector<int> singleNumber(vector<int>& nums) {
if(nums.size()==2&&nums[0]!=nums[1])return nums;
sort(nums.begin(),nums.end());
vector<int> ans;
for(int i=0;i<nums.size();i++)
{
if(nums[i]!=nums[i+1])
ans.push_back(nums[i]);
else i++;
}
return ans;
}

本文介绍了一种算法,用于从数组中找到仅出现一次的元素,而其他元素均出现两次。通过排序数组并比较相邻元素来实现,确保算法的时间复杂度为线性。
326

被折叠的 条评论
为什么被折叠?



