原始链接:点击打开链接
时间限制 1000 ms
内存限制 65536 KB
题目描述
Given an array with N integers where all elements appear three times except for one. Find out the one which appears only once.
输入格式
Several test cases are given, terminated by EOF.
Each test case consists of two lines. The first line gives the length of array N(1≤N≤105) , and the other line describes the N elements. All elements are ranged in [0,263−1] .
输出格式
Output the answer for each test case, one per line.
输入样例
4
1 1 1 3
10
1 2 3 1 2 3 1 2 3 4
输出样例
3
4
方法一:
排序之后对比相邻元素
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<math.h>
#include<algorithm>
using namespace std;
int main()
{
int number;
//int *a = new int(number)
long long int a[100000];
while(cin >> number){
for(int i=0; i<number; i++)
{
cin >> a[i];
}
//QuickSort<long long int>(a,number);
sort(a,a+number);
if(a[0]!=a[1])
cout << a[0]<< endl;
else if (a[number-1]!=a[number-2])
cout << a[number -1] <<endl;
else
for(int i=1; i<number-1; i++)
if(a[i]!=a[i-1] && a[i]!=a[i+1])
{
std::cout << a[i] << endl;
break;
}
}
return 0;
}
方法二:
将一次输入的所有数,获取每一位,保存在二维数组中。
若模三之后依然存在,则是只出现了一次。
算法复杂度是O(n),然而依旧不能AC...真是醉了。(原因超时)
#include <iostream>
#include <stdio.h>
#include <string.h>
#include<math.h>
#include<time.h>
using namespace std;
void fun(int *l, unsigned long long int a)
{
int len = sizeof( unsigned long long int)*8 ;
for(int i=0;i<len;i++)
{
l[i] += a >> i & 0x1;
}
}
int main()
{
unsigned long long int a;
int len = sizeof(unsigned long long int)*8 ;
int *l = new int [len];
int number;
unsigned long long int out;
while(scanf("%d",&number))
{
//time_t t0,t1;
//time(&t0);
memset(l,0,len*sizeof(int)); //memset 指针 覆盖的变量 覆盖的大小
for(int i=0;i<number;i++)
{
unsigned long long int temp ;
cin >> temp;
fun(l,temp); //将输入的数的每一位相加
}
out =0 ; //输出
for(int i=0;i<len;i++)
{
out += l[i]%3 * pow(2,i);
}
printf("%d\n",out);
//time(&t1);
//cout<<"time"<<t1-t0<<endl;
}
return 0;
}