题目链接: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?

题意:给定一整形数组,除了一个元素外的每一个元素都是出现3次,让找到那个仅出现一次的数。要求线性复杂度

结果直接看代码吧,有凝视

public int singleNumber(int nums[]) {
		int result = 0;
		int[] wei = new int[32];				//此数组用于记录nums中全部数各位中“1”出现的总次数
		
		for(int i=0; i<32; i++) {
			for(int j=0; j<nums.length; j++) {
				if((nums[j] & 1<<i) != 0) {		//假设num[j]第i为非零,则该i位置上的统计数wei[i]加1
					wei[i]++;
				}
			}
		}
		
		for(int i=0; i<32; i++) {	//对wei[i]的统计结果进行还原:假设wei[i]不是3的倍数。则该singleNumber在i位置上是1
			if(wei[i] % 3 != 0) {
				result += 1<<i;					
			}
		}
		
		return result;


posted on 2017-08-21 13:07  yutingliuyl  阅读(443)  评论(0编辑  收藏  举报