题目:
Given an array of integers, every element appears twice except for one. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
链接: http://leetcode.com/problems/single-number/
题解:
位运算,用异或处理掉出现两次的数字即可。
Time Complexity - O(n), Space Complexity - O(1)。
public class Solution { public int singleNumber(int[] A) { int result = 0; for(int i : A){ result ^= i; } return result; } }
Update:
public class Solution { public int singleNumber(int[] nums) { if(nums == null || nums.length == 0) return 0; int res = 0; for(int i : nums) res ^= i; return res; } }
二刷:
使用异或。a ^ b ^ a = b, 0 ^ b = b
Java:
Time Complexity - O(n), Space Complexity - O(1)。
public class Solution { public int singleNumber(int[] nums) { int res = 0; for (int i : nums) { res ^= i; } return res; } }
三刷:
Java:
public class Solution { public int singleNumber(int[] nums) { int res = 0; for (int i : nums) { res ^= i; } return res; } }
测试: