您的位置:首页 > 其它

Single Number

2016-06-02 15:25 295 查看
两道入门算法题,都是用位元算解决,学习一下。

1.LeetCode OJ 136. 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?


  解法:所有数字都出现两次,除了一个Single Number,可以考虑用 异或 (XOR) 解决,

    对a,a,b 来说,a ⊕ a = 0,所以可以用 ⊕ 消掉所有的出现两次的数,最后剩下的就是Single Number

  

class Solution {
public:
int singleNumber(vector<int>& nums) {
vector<int>::iterator it;
int result = nums[0];
it = nums.begin();
it++;
for(it ; it != nums.end() ; it++)
{
result = result ^ (*it);
}
return result;
}
};


2.kAri OJ (BUPT OJ) 84

  

题目描述

Given an array with 3integers 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



  这道题基本思路也是用位运算,不过比第一道麻烦一些,而且居然是第二题。。。

需要三个中间量,appear_once,appear_twice,appear_third,分别代表出现奇数次的数,出现偶数次的数,出现次数>=3的奇数

出现第一次保留在appear_once里,出现两次就保存在appear_twice,并且从appear_once里删除,同时满足appear_once和 appear_twice 的就是

appear_third,然后每次再用 满足 appear_once 且不满足 appear_third 就是出现一次的数,否则就是出现三次或三次以上的奇数。用appear_twice和 不满足appear_third的元素表示出现两次的数。最终经过一遍遍历就能确定出现一次的 Single Number。

#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
long long ele,appear_once,appear_twice,appear_third;   //出现1次的数,出现2次的数,出现次数>=3的奇数
int n;    //元素个数
ios_base::sync_with_stdio(false);
while (cin >>n) {
appear_once = appear_twice = 0;
while(n--){
cin >> ele;
appear_twice |= appear_once & ele;
appear_once = appear_once ^ ele;
appear_third = appear_once&appear_twice;
appear_once = (~appear_third) & appear_once;
appear_twice = (~appear_third) & appear_twice;
}
cout << appear_once << endl;
}
return 0;
}


p.s. c++的cin比c的scanf慢,因为默认的时候,cin与stdin总是保持同步的,也就是说这两种方法可以混用,

而不必担心文件指针混乱,同时cout和stdout也一样,两者混用不会输出顺序错乱。

正因为这个兼容性的特性,导致cin有许多额外的开销,如何禁用这个特性呢?

只需一个语句std::ios::sync_with_stdio(false);,这样就可以取消cin于stdin的同步了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: