LeetCode Single Number II

原题链接在这里:https://leetcode.com/problems/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?

题解:

这道题的关键就是要求no extra memory space. 所以就用到了bit manipulation.

用ones记录到当前计算的变量为止,二进制1出现"1次"(mod 3 之后的 1)的数位。用twos记录到当前计算的变量为止,二进制1出现"2次"(mod 3 之后的 2)的数位。当ones和twos中的某一位同时为1时表示二进制1出现3次,此时需要清零。

即用二进制模拟三进制计算, 最终ones记录的是最终结果。

Time Complexity: O(n).

Space: O(1).

AC Java:

 1 public class Solution {
 2     public int singleNumber(int[] nums) {
 3         if(nums == null || nums.length == 0){
 4             throw new IllegalArgumentException("Invalid input array.");
 5         }
 6         int ones = 0;
 7         int twos = 0;
 8         int xThrees = 0;
 9         for(int i=0; i<nums.length; i++){
10             twos |= ones&nums[i];
11             ones ^= nums[i];
12             xThrees = ~(ones&twos);
13             ones &= xThrees;
14             twos &= xThrees;
15         }
16         return ones;
17     }
18 }

另一方法是维护一个32位的数组,因为int 都是32位的,外层loop是对应每一位,内层loop是算所有的数在这一位上出现次数的和。

Mod 3 后剩下的就是那个只出现了一次的数。与Single Number类似.

Note:1. Check if current bit is 1 using:

nums[j] >> i & 1

但要注意的是bit operator: >>, & 都比 == operator 运算级别低,所以要加括号。

2.  给了一个array代表2进制的数,转化成10进制的数就是用

res += bitCounter[i]<<i

Time Complexity: O(n). Space: O(1).

AC Java:

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

跟上Single Number III.

转载于:https://www.cnblogs.com/Dylan-Java-NYC/p/4825049.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值