zoukankan      html  css  js  c++  java
  • 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;
    }
  • 相关阅读:
    C#中处理鼠标和键盘的事件
    C#中处理鼠标和键盘的事件
    C#中处理鼠标和键盘的事件
    mpich2安装
    算法题推箱子
    LINUX终端下windows盘的位置
    Linux头文件和库文件添加环境变量与GCC编译器添加INCLUDE与LIB环境变量
    第九章顺序容器重学C++之《 C++ PRIMER》
    sed中使用变量
    抛出异常
  • 原文地址:https://www.cnblogs.com/mickole/p/3673607.html
Copyright © 2011-2022 走看看