LeetCode - 137 - Single Number II

xiaoxiao2021-02-28  77

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

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

数组中只出现一次的数,其余都出现三次。

不得不说,位运算真的是神奇方便快捷,感觉如果精通位运算,很多问题都不是问题哎

思路:所有的数都出现过三次,那每一位上加起来一定模3为0,若不为0,那就是只出现过一次的那个数咯

时间复杂度O(32n),空间O(1)

class Solution { public: int singleNumber(vector<int>& nums) { int ans = 0; for (int i = 0; i < 32; ++i) { int sum = 0; for (int j = 0; j < nums.size(); ++j) { if ((nums[j]>>i) & 1 == 1) { sum++; sum %= 3; } } if (sum) ans += sum << i; } return ans; } };

评论区有大神写了个写法,没看懂,先码一下

public int singleNumber(int[] A) { int ones = 0, twos = 0; for(int i = 0; i < A.length; i++){ ones = (ones ^ A[i]) & ~twos; twos = (twos ^ A[i]) & ~ones; } return ones; }

转载请注明原文地址: https://www.6miu.com/read-75868.html

最新回复(0)