【LeetCode】- Single Number(从数组中找出只出现一次的数字)

[问题:]

Given an array of integers, every element appearstwiceexcept for one. Find that single one.
Note:Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?

翻译:给定一个整数数组,数组中所有元素都出现了两次,只有一个元素只出现了一次,找出这个只出现了一次的元素。

[ 解法:]
①. 常规解法:时间复杂度为 O(n²),没能通过
/**
 * Time Limit Exceeded 
 * 时间复杂度为:O(n²),无法通过
 */
public class Solution1 {
	public int singleNumber(int[] arr) {
		int count = 0;
		for (int i = 0; i < arr.length; i++) {
			for (int j = 0; j < arr.length; j++) {
				if (arr[i] == arr[j]) {
					count++;
				}
			}
			if (count == 1) {
				return arr[i];
			} else {
				count = 0;
			}
		}
		return -1;
	}

	public static void main(String[] args) {
		int[] arr = { 0, 1, 1, 2, 2, 3, 0 };
		System.out.println(new Solution1().singleNumber(arr));
	}
}
②. 标准解法:使用异或运算
这个程序用了个小技巧:一个整数和它本身异或之后得到值是0,0与其他整数异或得到的是这个整数本身
/**
 * 利用异或的可交换性
 */
public class Solution2 {
	public int singleNumber(int[] arr) {
		// invalid check
		if (arr.length == 0) {
			return -1;
		}
		int result = 0;
		for (int i = 0; i < arr.length; i++) {
			result = result ^ arr[i];
		}
		return result;
	}

	public static void main(String[] args) {
		int[] arr = { 0, 1, 1, 2, 2, 3, 0 };
		System.out.println(new Solution2().singleNumber(arr));
	}
}

[ 拓展: ]

异或运算的两个法则:

①.a ^ b = b ^ a

②. a ^ b ^ c = a ^ (b ^ c) = (a ^ b) ^ c

^ 假 = 真  假^ 真 = 真  假^ 假 = 假  真^ 真 = 假

/**
 * 不使用第三个变量,交换两个变量的值
 */
public class Swap {
	public static void main(String[] args) {
		int a = 1, b = 2;
		System.out.println("交换前: a = " + a + " , b = " + b);
		a = a ^ b;
		b = a ^ b;
		a = a ^ b;
		System.out.println("交换后: a = " + a + " , b = " + b);
	}
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值