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?
Subscribe to see which companies asked this question.
AC:
class Solution {
public:
int singleNumber(vector<int>& nums) {
int n = nums.size();
sort(nums.begin(), nums.end());
if(nums[0] != nums[1])
return nums[0];
if(nums[n-1] != nums[n-2])
return nums[n-1];
for(int i = 1; i < n-1; i ++)
{
if(nums[i] != nums[i-1] && nums[i] != nums[i+1])
return nums[i];
}
}
};
转载请注明原文地址: https://ju.6miu.com/read-23406.html