Single Number I

Problem:Single Number I

Given an array of integers, every element appears twice except for one. Find that single one.

Note:Your algorithm should have alinear runtime complexity. Could you implement it without using extra memory?

代码如下:

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


这个问题主要考虑到亦或运算符的运算规则:

1^1=0; 0^0=0; 1^0=1;

a^b^c=a^(b^c)=(a^b)^c;

我submit时一开始并没有想到这种方法,而是采用了先快排,在查找的办法,测试也可以通过,但时间复杂度是n*logn,可能是在n直很小时,无法区分这两种复杂度的区别。代码如下:

#include <algorithm>
using namespace std;

class Solution {
public:
	int singleNumber(int A[], int n) {
		sort(&A[0], &A[n]);
		for(;--n>=0;){
			if(A[n]!=A[n-1]){
				return A[n];
			}
			else if(n == 0){
				return A[0];
			}
			else
				n--;
		}
	}
};



这种方式利用stl库里的sort()算法,先快排,再查找。

另外leetcode oj上不能使用cout等,否则会报错,一开始的错误千奇百怪,后来才发现。本人新手,还是要多加练习啊!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值