[LeetCode]Single Number

本文针对LeetCode上的Single Number问题提供了解决方案,利用异或运算特性在O(n)的时间复杂度内找出数组中唯一出现一次的数字,并附带C++实现代码。

题目:

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?

来源:http://oj.leetcode.com/problems/single-number/


思路:

异或运算

1.a ^ a = 0

2. a^0=a
3. a ^ b = b ^a
4. a ^ b ^ c = a ^ (b ^ c) = (a ^ b) ^ c;
5. a ^ b ^ a= b.

从上面几个算式可以知道:因为数组中其他元素都出现2次,只有一个出现1次,所以循环整个数组,依次异或,结果就肯定是那个只出现1次的数字。


C++ AC代码:

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

运行时间:44ms

测试代码:

/*
 *Created by RogerKing
 *Email:jin_tengfei@163.com
 */


#include <iostream>

using namespace std;

int singleNumber(int A[], int n) 
{
	int s = A[0];
	for( int i=1; i<n; ++i)
		s^=A[i];
	return s;
 }

void display(int A[],int n)
{
	cout<<"The array:";
	for( int i=0; i<n ; i++)
		cout<<A[i]<<" ";
	cout<<endl;
}

int main()
{
	int A[9]={1,2,3,4,5,4,3,2,1};
	display(A,9);
	cout<<"The single one:"<<singleNumber(A,9)<<endl;
	return 0;
}


PS:感觉自己水平还低的可以啊,先从LeetCode中AC Rates最高的开始做吧,好好研究《C++ Primer》,好好准备。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值