leetcode之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?

意思就是:

给定一个整型数组,里面只有一个元素出现过一次,剩余元素都是出现两次。请找出只出现过一次的元素。

注意:时间复杂度是线性的,同时空间复杂度也不能使用额外空间。

解题思路:

思路一:可以使用双层嵌套循环,每一个元素都和其他元素比较,如果有相同的,则证明这个元素不是只出现一次的。但是时间复杂度是n的平方,不符合题意。

思路二:两个相同元素异或之后会得到0.所以把数组里的所有元素都异或,得到的值即为那个只出现一次的元素。

代码如下:

class Solution {
public:
    int singleNumber(int A[], int n) {
        	int output = 0;
			if(n == 0){
				return 0;
			}
			else{
				int i,result = A[0];
				for(i=1;i<n;i++){
					result ^= A[i];
				}
				output = result;
			}
			return output;
    }
};





你可能感兴趣的:(LeetCode,C++,算法)