码迷,mamicode.com
首页 > 其他好文 > 详细

136.Single Number

时间:2015-01-30 09:10:45      阅读:247      评论:0      收藏:0      [点我收藏+]

标签:

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 itwithout using extra memory?

 

 

 

第二种不使用额外空间的方法,比第一种慢一点点~


//main.cpp
#pragma once
#include<iostream>
using namespace std;


int singleNumber2(int A[], int n)
{
	int result = *A;
	for (int i = 1; i < n; i++)
		result = result^A[i];
	return result;
}

int singleNumber1(int A[], int n)
{
	for (int i = 1; i < n; i++)
		*A = *A^A[i];
	return *A;
}

void main()
{
	int a[] = { 1, 2, 3, 4, 5, 6, 5, 4, 3, 2, 1 };
	int n = sizeof(a) / sizeof(int);
	cout << singleNumber(a, 11) << endl;
	system("pause");
}


136.Single Number

标签:

原文地址:http://blog.csdn.net/hgqqtql/article/details/43278665

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!