leetcode 137 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?

Subscribe to see which companies asked this question


class Solution {
public:
	int singleNumber(vector &nums) {
		int len = nums.size(), res = 0;

		for(int i = 0; i < 32; i++) {
			int cnt = 0;
			for(int j = 0; j < len; j++) {
				if((j >> i) & 1) cnt+=1;
			}
			if(cnt%3) {
				res |= ((cnt%3) << i);
			}
		}

		return res;
	}
}




你可能感兴趣的:(Leetcode)