您的位置:首页 > 其它

LeetCode 137 Single Number II(仅仅出现一次的数字 II)(*)

2017-08-06 15:37 405 查看

翻译

给定一个整型数组,除了某个元素外其余的均出现了三次。

找出这个元素。

备注:
你的算法应该是线性时间复杂度。

你能够不用额外的空间来实现它吗?


原文

Given an array of integers, every element appears three times except for one. Find that single one.

Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?


分析

这道题我并没有依照题目线性时间和不使用额外存储的要求来完毕,确实非常难的一道题……

我也就这水平了,以下的解决方式没有使用额外存储时间只是时间已经超了。

class Solution {
public:

int singleNumber(vector<int>& nums) {
sort(nums.begin(), nums.end());
for (int i = 1; i < nums.size() - 1; ++i) {
if ((nums[i] != nums[i - 1]) && (nums[i] != nums[i + 1]))
return nums[i];
}
if (nums[0] != nums[1]) return nums[0];
else if (nums[nums.size() - 1] != nums[nums.size() - 2])
return nums[nums.size() - 1];
}
};


与之相关的还有两道题。大家能够看看:

LeetCode 136 Single Number(仅仅出现一次的数字)

LeetCode 260 Single Number III(仅仅出现一次的数字 III)(*)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: