leetcode Single Number II

来源:互联网 发布:mp3音乐下载软件 编辑:程序博客网 时间:2024/06/04 20:13

上题:

Given an array of integers, every element appears three times except for one. Find that single one.

Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?

这题和2个数的有点不一样,这里我采用一个长度为32的数组,记录原数组中每一位的个数,将32的数组中每个数字都取余3便得到了不同的那个数字。代码:
class Solution {public:int singleNumber(int A[], int n){int tmp[32];for (int i = 0; i < 32; i++){tmp[i] = 0;}for (int i = 0; i < n; i++){int k = 1;for (int j = 0; j < 32; j++){if (k & A[i]){tmp[j]++;}k = k<<1;}}for (int i = 0; i < 32; i++){tmp[i] = tmp[i] % 3;}int nRet = 0;for (int i = 0; i < 32; i++){nRet += tmp[i]<<i;}return nRet;}};

0 0
原创粉丝点击