Single Number 一次失败的AC之旅

原始链接:点击打开链接

时间限制 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(1N105) , and the other line describes the  N elements. All elements are ranged in  [0,2631] .

输出格式

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
这题换了两个方法还是不能AC...真是醉了

方法一:

排序之后对比相邻元素

#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;
}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值