【LeetCode OJ 136】Single Number

题目链接:https://leetcode.com/problems/single-number/

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

解题思路:题意为:给定一个数组,只有一个元素出现了一次,其它元素都出现了两次,找出那个只出现一次的数。可以遍历数组,分别进行异或运算。

注:异或运算:相同为0,不同为1。遍历并异或的结果就是那个只出现了一次的数。

示例代码:

public class Solution 
{
	public int singleNumber(int[] nums) 
	{
		int result=nums[0];
		for (int i = 1; i < nums.length; i++)
		{
			result^=nums[i];
		}
		return result;
	}  
}


你可能感兴趣的:(java,LeetCode)