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;
    }
  • 相关阅读:
    欧几里得算法及扩展欧几里得(含)
    RP
    P1734_最大约数和
    The 2017 ACM-ICPC Asia East Continent League Final记录
    【数据结构】bzoj1651专用牛棚
    【数据结构】bzoj1455罗马游戏
    【数据结构】bzoj1636/bzoj1699排队
    【数据结构】bzoj3747Kinoman
    【计算几何】奇特的门
    Topcoder SRM 608 div1 题解
  • 原文地址:https://www.cnblogs.com/mickole/p/3673607.html
Copyright © 2011-2022 走看看