[LeetCode] 137. Single Number II

Given an integer array nums where every element appears three times except for one, which appears exactly once. Find the single element and return it.

You must implement a solution with a linear runtime complexity and use only constant extra space.

Example 1:

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

Example 2:

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

Constraints:

  • 1 <= nums.length <= 3 * 104
  • -231 <= nums[i] <= 231 - 1
  • Each element in nums appears exactly three times except for one element which appears once.

只出现一次的数字 II。

给你一个整数数组 nums ,除某个元素仅出现 一次 外,其余每个元素都恰出现 三次 。请你找出并返回那个只出现了一次的元素。

你必须设计并实现线性时间复杂度的算法且不使用额外空间来解决此问题。

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/single-number-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 题目总结

posted @ 2020-04-02 01:47  CNoodle  阅读(403)  评论(0编辑  收藏  举报