[LeetCode] 137. Single Number II

Given a non-empty 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?

Example 1:

Input: [2,2,3,2]
Output: 3

Example 2:

Input: [0,1,0,1,0,1,99]
Output: 99

只出现一次的数字II。

题意跟版本一几乎一样,唯一不同的地方是版本一其他数字出现了两次,版本二其他数字出现了三次。这道题我先写一个我自己能记得住的思路吧,这个思路能延伸到找一个出现过K次的数字。建立一个32位的数字,来统计每一位上出现1的次数。如果某一个数字出现了三次,那么只要对32位上每一位%3,为0的那些数位就能拼凑出这个出现了3次的数字了。下面这个截图帮助理解,

时间O(n) - 遍历了N个数字

空间O(1)

Java实现

 1 class Solution {
 2     public int singleNumber(int[] nums) {
 3         int ans = 0;
 4         for (int i = 0; i < 32; i++) {
 5             int sum = 0;
 6             for (int j = 0; j < nums.length; j++) {
 7                 if (((nums[j] >> i) & 1) == 1) {
 8                     sum++;
 9                     sum %= 3;
10                 }
11             }
12             if (sum != 0) {
13                 ans |= sum << i;
14             }
15         }
16         return ans;
17     }
18 }

JavaScript实现

 1 /**
 2  * @param {number[]} nums
 3  * @return {number}
 4  */
 5 var singleNumber = function(nums) {
 6     let res = 0;
 7     for (let i = 0; i < 32; i++) {
 8         let sum = 0;
 9         for (let num of nums) {
10             sum += (num >> i) & 1;
11             sum %= 3;
12         }
13         if (sum != 0) {
14             res |= sum << i;
15         }
16     }
17     return res;
18 };

相关题目

136. Single Number

137. Single Number II

260. Single Number III

LeetCode 题目总结

原文地址:https://www.cnblogs.com/cnoodle/p/12617191.html