• LeetCode137:Single Number II


    题目:

    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?

    解题思路:

    这题比Single Number稍难些,不能用异或解决,但排序和bitmap还是可以的,只是时间复杂度和空间复杂度要多些

    这里我用另一种方式实现,根据所给数组中元素的规律,可利用每一bit位上1的个数进行解决,直接看代码吧

    实现代码:

    #include <iostream>
    
    using namespace std;
    /*
    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?
    */
    class Solution {
    public:
        int singleNumber(int A[], int n) {
            int once = 0;
            for(int i = 0; i < 32; i++)
            {
                int one_num = 0;//bit为第i位1的个数 
                for(int j = 0; j < n; j++)
                    if((A[j] >> i) & 1 == 1)
                        one_num++;
                //因为数组中只有一个数出现一次,其他数都出现三次,
                //所以除非要找数的当前bit位为1,否则one_num为3的倍数 
                if(one_num % 3)
                    once += (1 << i);
    
            }
            return once;
            
        }
    };
    
    int main(void)
    {
        int arr[] = {2,4,5,5,4,1,2,4,2,5};
        int len = sizeof(arr) / sizeof(arr[0]);
        Solution solution;
        int once = solution.singleNumber(arr, len);
        cout<<once<<endl;
        return 0;
    }
  • 相关阅读:
    HOT: AgentFramework 即将发布
    关于配置 Apache + SVN 1.5 + SSL
    LINQ to SQL(LINQ2SQL) vs. ADO.NET Entity Framework(ADOEF)ccBoy版 阅读笔记
    关于导出属性
    linq to sql 与linq to entities的选择
    linq to sql 算ORM吗?
    匿名方法实现(转)
    Aop中动态横切与静态横切
    老张的灵魂——敏捷回顾
    忙于webmis中
  • 原文地址:https://www.cnblogs.com/mickole/p/3673607.html
Copyright © 2020-2023  润新知