Question:
Given an array of integers, every element appears three times except for one, which appears exactly once. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
Answer:
class Solution {
public:
int singleNumber(vector<int>& nums) {
int i=0;
if(nums.size()==1)
return nums[i];
if(nums.size()==2)
return NULL;
if(nums.size()==3)
return NULL;
sort(nums.begin(), nums.end());
for(i==0;i<nums.size();i=i+3)
{
if(nums[i]!=nums[i+1])
return nums[i];
}
}
};run code results:
Your input
[1 1 0 1 9 8 0 8 9 0 9 8 4 7 5 7 5 7 5]
Your answer
4
Expected answer
4
本文介绍了一种算法,该算法能在线性时间内找出数组中仅出现一次的整数,而其他所有元素都恰好出现了三次。通过排序并遍历数组来实现这一目标,特别考虑了数组长度为1、2或3的特殊情况。
708

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



