`
SunnyYoona
  • 浏览: 367080 次
社区版块
存档分类
最新评论

LeetCode之Single Number II

 
阅读更多

【题目】

Given an array of integers, every element appearsthreetimes except for one. Find that single one.

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

【题意】

给定一个整数数组,每个元素出现了三次,除了一个。找出那个出现一次的数字。

注意:

你的算法应该一个线性时间复杂度完成。你能不能无需使用额外的内存来完成它

【分析】

方法 1:创建一个长度为 sizeof(int) 的数组 count[sizeof(int)],count[i] 表示所有元素的 1 在 i 位出现的次数。

如果 count[i] 是 3 的整数倍,则忽略;否则就把该位取出来组成答案。
方法 2:用 ones 记录到当前处理的元素为止,二进制 1 出现“1 次”(mod 3 之后的 1)的有哪些二进制位;

用 twos 记录到当前计算的变量为止,二进制 1 出现“2 次”(mod 3 之后的 2)的有哪些二进制位。

当 ones 和 twos 中的某一位同时为 1 时表示该二进制位上 1 出现了 3 次,此时需要清零。

即用二进制模拟三进制运算。最终 ones 记录的是最终结果。

【代码1】

/*********************************
*   日期:2014-01-26
*   作者:SJF0115
*   题号: Single Number II
*   来源:http://oj.leetcode.com/problems/single-number-ii/
*   结果:AC
*   来源:LeetCode
*   总结:
**********************************/
#include <iostream>
#include <stdio.h>
#include <string.h>
using namespace std;

class Solution {
public:
    int singleNumber(int A[], int n) {
        int i,j;
        //整数字长
        int w = sizeof(int) * 8;
        int result = 0;
        //count[i]表示所有数字在二进制表示中1在第i位上的次数
        int count[w];
        //初始为0
        for(i = 0;i < w;i++){
            count[i] = 0;
        }
        for(i = 0;i < n;i++){
            for(j = 0;j < w;j++){
                //二进制中第j位
                count[j] += (A[i]>>j) & 1;
                //count[j]是3的倍数,这是由那些出现3次数字产生的则置为0
                count[j] %= 3;
            }//for
        }//for
        for(i = 0;i < w;i++){
            //printf("%d ",count[i]);
            result += (count[i] << i);
        }
        return result;
    }
};
int main() {
    Solution solution;
    int result;
    int A[] = {2,2,2,6,4,4,4};
    result = solution.singleNumber(A,7);
    printf("Result:%d\n",result);
    return 0;
}



【代码2】

class Solution {
public:
    int singleNumber(int A[], int n) {
        int ones = 0, twos = 0, threes = 0;
        for (int i = 0; i < n; ++i) {
            twos |= (ones & A[i]);
            ones ^= A[i];
            threes = ~(ones & twos);
            ones &= threes;
            twos &= threes;
        }
        return ones;
    }
};


分享到:
评论

相关推荐

    leetcode Single Number II - 位运算处理数组中的数 - 代金桥 - 博客园1

    扩展二:给定一个包含n个整数的数组,有一个整数x出现b次,一个整数y出现c次,其他所有的数均出现a次,其中b和c均不是a的倍数,找出x和y。中每一位二进制位1出

    LeetCode最全代码

    137 | [Single Number II](https://leetcode.com/problems/single-number-ii/) | [C++](./C++/single-number-ii.cpp) [Python](./Python/single-number-ii.py) | _O(n)_ | _O(1)_ | Medium ||| 190 | [Reverse Bits]...

    颜色分类leetcode-leetcode.etc:OJ、leetcode等解决方案

    颜色分类leetcode leetcode.etc My solutions of the problems in Online judge website, leetcode, lintcode, etc. leetcode: 13 problems solved lintcode: 49 problems solved Title URL Solution Difficulty ...

    Leetcode的ac是什么意思-LeetCodeInJava:leetcode-java

    Leetcode的ac是什么意思 LeetCodeInJava List #98 Validate Binary Search Tree #100 Same Tree #104 Maximum Depth of Binary Tree #122 Best Time to Buy and Sell Stock II #136 Single Number #150 Evaluate ...

    leetcode答案-leetcode-java:leetcode的Java代码

    leetcode 答案leetcode-java leetcode.com ...II Remove Duplicates from Sorted List com.leetcode.string Single Number com.leetcode.tree Balanced Binary Tree Maximum Depth of Binary Tree Same Tree

    LeetCode:LeetCode解决方案

    preorder-traversal链表reorder-list链表linked-list-cycle-ii链表linked-list-cycle动态规划word-break-ii动态规划word-break链表copy-list-with-random-pointer复杂度single-number-ii复杂度single-number动态规划

    leetcode切割分组-leetcode:leetcode

    136_single_number.py # 位操作:异或(xor)操作 x ^ 0 = x; x ^ x = 0 sum 001_two_sum.py # 求list中能加和成指定值的两个位置 015_3_sum**.py # 求list中能加和成0的三个值 数列 004_median_of_two_sorted_arrays....

    LeetCode2 Add Two Numbers

    The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list. You may assume the two numbers do not contain any leading ...

    LeetCode:LeetCode题解

    LeetCode LeetCode题解 传送门 # 标题 解决方案 困难 笔记 1个 简单的 3 简单的 7 简单的 9 简单的 22 中等的 26 简单的 27 Remove_Element ... Single_NumberII Java 中等的 167 Two_Sum_II_Input_

    leetcode分类-LeetCode:LeetCode在线裁判C++

    SingleNumber 其他算法 各种SingleNumber变种 LinkListCycle I II 其他变种 编程之美 Preorder Traversal Inorder Traver sal postorder 非递归 不用栈! 字符串常用操作 字符串 各种转换 Pow(x,n) 优化 ...

    leetcode和oj-leetCode:尝试一些OJ

    Single Number 52.2% Easy 371 两个整数的和 51.6% Easy 104 二叉树的最大深度 50.1% Easy 325% Add the Easy 389.数字 49.9% 简单 226 反转二叉树 48.9% 简单 283 移动零点 46.9% 简单 404 左叶总和 45.5% 简单 383...

    dna匹配leetcode-leetcode:leetcode刷题

    dna匹配 leetcode leetcode刷题--C++ ...Single Number 异或 Copy List with Random Pointer 单链表 map Max Points on a Line 斜率 map, int&gt; Fraction to Recurring Decimal map long long 正负号 Repeated DNA S

    leetcode答案-leetcode:leetcode

    II mod之后,可能数学公式就不能简单地给出答案了。但对我来说,其实和前一题没区别。动态规划处理这种问题,早就是牛刀杀鸡了。。 Single Number 碰巧我知道异或的解法。如果不知道的话,想想还是有点费事的。 ...

    leetcoderuntimeerrorjava-leetcode:面试准备的数据结构和算法

    singleNumber ( self , nums : List [ int ]) -&gt; int : 它是所谓的“类型提示”(或“函数注释”;自 Python 3.0 起可用)。 -&gt; List[int] 意味着函数应该返回一个整数列表。 nums: List[int], target: int 表示 ...

    leetcode添加元素使和等于-LeetCode:力扣唱片

    leetcode添加元素使和等于 LeetCode LeetCode Record 归并快排的区别: 思想不同:归并从局部到整体,快排...single out the missing number. How? First, we need to understand the properties of XOR: firstly, XOR'

    LeetCode去除数组重复元素-Arithmetic-Swift:一些算法的swift实现

    LeetCode去除数组重复元素 Arithmetic-Swift 一些算法的swift实现 桶排序 冒泡排序 快速排序 ##正好看见LeetCode可以刷Swift的题目 开始慢慢刷 swift有playground ...Number 石头游戏 292. Nim Gam

    leetcode蓄水池JAVA-leetcode-with-[removed]:wrapped_gift:用各种解决方案和单元测试来练习Leetcode

    https://leetcode.com/problems/single-number/ level : - easy tags : - recursive - linked list solutions : - reverseList - runtime : 52 ms, beats 99.80% - memory : 35 MB, beats 47.37% - ...

    lrucacheleetcode-LeetCode_30Day:力扣30天挑战赛

    lru缓存leetcode 力扣_30天 力扣 30 天挑战赛 日 问题描述 问题和解决方案链接 Git 解决方案页面 1 SINGLE NUMBER 2 HAPPY NUMBER 3 MAXIMUM SUBARRAY 4 Move Zeroes 5 Best Time to Buy and Sell Stock II 6 GROUP ...

    leetcode浇花-LCSolutions:我的力扣解决方案

    leetcode 浇花力扣解决方案 简单的 #0001 - Two Sum #0007 - Reverse Integer #0009 - Palindrome Number #0035 - Search Insert Position #0058 - Length of Last Word #0066 - Plus One #0083 - Remove Duplicates...

    gasstationleetcode-leetcode-in-niuke:在牛客网上的在线编程中的leetcode在线编程题解

    single-number 动态规划 candy 贪心 gas-station 动态规划 palindrome-partitioning-ii 动态规划 triangle 树 sum-root-to-leaf-numbers 动态规划 distinct-subsequences 递归 valid-palindrome 模拟 pascals-...

Global site tag (gtag.js) - Google Analytics