码迷,mamicode.com
首页 > 编程语言 > 详细

Java for LeetCode 137 Single Number II

时间:2015-06-03 17:29:50      阅读:136      评论:0      收藏:0      [点我收藏+]

标签:

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?

解题思路一:

一个int的长度是32,因此可以开一个长度为32的数组,表示nums中所有元素各位1的个数和,然后%3即可得到结果。

JAVA实现如下:

	public int singleNumber(int[] nums) {
		int[] bitnum = new int[32];
		int res = 0;
		for (int i = 0; i < 32; i++) {
			for (int j = 0; j < nums.length; j++)
				bitnum[i] += (nums[j] >> i) & 1;
			res += (bitnum[i] % 3) << i;
		}
		return res;
	}

 解题思路二:

分别用三个变量bit0、bit1、bit2表示nums元素中1个数为0、1、2的分布,最后返回bit1即可,JAVA实现如下:

	public int singleNumber(int[] nums) {
		int bit0 = ~0, bit1 = 0, bit2 = 0, oldTwo;
		for (int i = 0; i < nums.length; i++) {
			oldTwo = bit2;
			bit2 = (bit1 & nums[i]) | (bit2 & ~nums[i]);
			bit1 = (bit0 & nums[i]) | (bit1 & ~nums[i]);
			bit0 = (oldTwo & nums[i]) | (bit0 & ~nums[i]);
		}
		return bit1;
	}

 

Java for LeetCode 137 Single Number II

标签:

原文地址:http://www.cnblogs.com/tonyluis/p/4549387.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!