[leetcode] 137. Single Number II 解题报告

来源:互联网 发布:php exec java 编辑:程序博客网 时间:2024/05/29 04:36

题目链接:https://leetcode.com/problems/single-number-ii/

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?


思路:分别计算到当前位置出现一次的数, 出现两次的数, 出现三次的数(用于消除出现在一次和二次的结果中出现三次的数). 其中出现一次的数很好统计, 只要异或就行, 这样最后保留的就是出现奇数次的数. 统计出现两次的数就要看这个数之前是不是出现过, 也就是和出现一次的数按位与就行了. 统计出现三次的数就要他是不是出现奇数次, 并且至少出现了两次. 这样当我们统计好这三个量之后还要消除在出现one中出现三次的数, two中出现三次的数. 这样在one和two中剩下就是只出现一次和两次的数.

代码如下:

class Solution {public:    int singleNumber(vector<int>& nums) {        int one =0, two=0, three=0;        for(auto val: nums)        {            two |= (val&one);            one ^= val;            three = (one&two);            one ^= three;            two ^= three;        }        return one;    }};


参考:http://www.cnblogs.com/daijinqiao/p/3352893.html

0 0
原创粉丝点击