您的位置:首页 > 其它

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

2016-02-18 19:21 525 查看

翻译

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

备注:
你的算法应该是线性时间复杂度。你可以不用额外的空间来实现它吗?


原文

[code]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?


分析

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

我也就这水平了,下面的解决方案没有使用额外存储时间不过时间已经超了。

[code]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)(*)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: