微软面试100题-61(找出数组中两个只出现一次的数字)



61.找出数组中两个只出现一次的数字(数组)
题目:一个整型数组里除了两个数字之外,其他的数字都出现了两次。
请写程序找出这两个只出现一次的数字。要求时间复杂度是O(n),空间复杂度是O(1)。

分析:这是一道很新颖的关于位运算的面试题。

package com.interview.algorithm;
/*
 * 一个数和自己xor,返回0。1^1=0 0^0=0 1^0 = 1 0^1 = 1
 */
public class OnceChar {
	public int AllXor(char[] c){
		int all = 0;
		for(int i = 0; i < c.length; i++){
			all = all^c[i];
		}
		return all;
	}
	//返回倒数几位
	public int getFirstOne(int num){
		int pos = 1;
		while((num & 0x01) == 0){
			num = num >> 1;
			pos++;
		}
		return pos;
	}
	
	public char[] getOnceChar(char[] c){
		int xor = this.AllXor(c);
		int firstOne = this.getFirstOne(xor);
		char[] res = new char[2];
		int num1 = 0; int num2 = 0;
		for(int i = 0; i < c.length; i++){
			if(this.isOne(firstOne, c[i]) == 0){
				num1 = num1 ^ c[i];
			}else{
				num2 = num2 ^ c[i];
			}
		}
		res[0] = (char)num1;
		res[1] = (char)num2;
		return res;
	}
	//如果最后一位是1,不用移位
	public int isOne(int pos, char c){
		int i = c >> (pos - 1);
		int isOne = i & 0x01;
		return isOne;
	}
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		String str = "AABBCDDEFF";
		OnceChar once = new OnceChar();
		char[] res = once.getOnceChar(str.toCharArray());
		System.out.println(res[0]);
		System.out.println(res[1]);
	}

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值