好题 BUPT OJ84 SINGLE NUMBER

44 篇文章 3 订阅

题目描述

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

这题居然是第二题...瞎了...借鉴了leetcode上的一些讨论结果

主要思路是对所有数字进行异或运算, 模拟二进制加法

 因为异或运算有a⊕b⊕a=b这样的性质, 所以可以设app_1, app_2代表出现一次和两次的数, 用not_three代表所有没有出现三次的数, 通过位运算, 最后app_2和出现三次的数被清0, 只剩下app_1, 也就是结果

有人提到前面解释不清楚,那我更新一下。异或运算本质是二进制位运算,app_1保留出现奇数次的数,一旦出现两次就将进入app_2并从app_1中擦除,如果出现三次就会因为同时出现在app_1和app_2中而被not_three擦除,每次app_1和app_2都要和not_three进行一次与运算确保app_1和app_2中没有存放大于等于三次的数, 所以最终保留的app_1就是只出现一次的数。这个办法通过改变变量个数可以满足一切的查找唯一出现次数的问题,可设app[]进行保存。

算法复杂度是O(n)


/*
USER_ID: test#birdstorm
PROBLEM: 84
SUBMISSION_TIME: 2014-03-01 17:23:31
*/
#include<stdio.h>
 
main()
{
    long long x, n, app_1, app_2, not_three;
    while(scanf("%lld",&n)!=EOF){
        app_1=0, app_2=0;
        while(n--){
            scanf("%lld",&x);
            app_2 |= app_1&x;
            app_1 ^= x;
            not_three = ~(app_1&app_2);
            app_1 = not_three&app_1;
            app_2 = not_three&app_2;
        }
        printf("%lld\n",app_1);
    }
    return 0;
}



  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值