LeetCode 137. Single Number II

来源:互联网 发布:世界地图销售网络下载 编辑:程序博客网 时间:2024/05/17 07:41

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?

Solve it according to bits of different position, we thus need to verify the 32 bits.  (suppose it is a 32-bit machine)

int singleNumber(vector<int>& nums) {    int target = 0;    for(int i = 0; i <= 31; ++i) {        int count = 0;        for(int j = 0; j < nums.size(); ++j) {            count = count + ((nums[j] >> i) & 0x1);        }        target = target | ((count % 3) << i);    }    return target;}

Time Complexity is 32O(n). It can pass leetCode, not sure whether this is the most optimized solution though.

0 0
原创粉丝点击