LeetCode 题解

SingleNumber

题目:Given an array of integers, every element appears twice except for one. Find that single one.

题解:利用了a^a = 0的性质,将数组中的所有数异或起来记得到答案。

代码:

int singleNumber(int* nums, int numsSize) {
    int ans = 0;
    int i = 0;
    
    for(; i < numsSize; i++)
    {
        ans ^= nums[i];
    }
    return ans;
}


以后一定要记住考虑位运算的性质!!!!奇思妙想!!!!


Add Digits

题目:

Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.

For example:

Given num = 38, the process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return it.

题解:

这是一个求digital root的题。先贴wiki:https://en.wikipedia.org/wiki/Digital_root   

之后再来细看


Factorial Trailing Zeroes

题目:Given an integer n, return the number of trailing zeroes in n!.

思路:求乘积中0的个数,其实就是求乘数分解后有多少对2和5,因为每一对2和5都能在乘积中产生1个0。针对本题是n!,那么连续的正整数中因子2一定比因子5多,所以本题实际上就是求:在1到n这连续n个正整数中共有多少个因子5.

直接的做法是对1到n中的每一个数都求一遍,然后加起来,代码如下:

int trailingZeroes(int n) {
    int i = 0, calc = 0;
    int temp = 0;

    for(i = 1; i <= n; i++)
    {
        temp = i;
        while(temp % 5 == 0)
        {
            calc++;
            temp /= 5;
        }
    }
    return calc;
}

复杂度为O(nlogn)。

进一步思考:有因子5的正整数均可以写作5*k,那么其实需要考虑的数就变成了:5*1,5*2 。。。5*k,其中5 * k <= n,即k = ( n / 5 );

这些数中至少含有一个5,其余可能含有5的部分为1,2,3..k,那么需要求出这部分中含有的因子5的个数,这就变成了一个规模更小的子问题,同样可解。

代码如下:

int trailingZeroes(int n) {
    int ans = 0;
    
    while(n != 0)
    {
        n /= 5;
        ans += n;
    }
    return ans;
}


Majority Element
Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.
You may assume that the array is non-empty and the majority element always exist in the array.

看到这道题时,我第一个想到的就是之前禹哥跟我提到过的办法:统计每个数每个二进制位上1的个数,最后将所有1出现次数大于n/2的位选出来组成数,就是答案。因为题中已经说明了所求的majority element出现的次数大于n/2,则对应的二进制位上的1的个数也必然大于n/2。

贴上代码:

#include <math.h>

int lowbit(int x)
{
    return x&(-x);
}

int mypow(int i)
{
    return 1<<i;
}

int majorityElement(int* nums, int numsSize) {
    int stat[32];
    int i = 0;
    int res = 0;
    int ans = 0;
    
    for(i = 0; i < 32; i++)
    {
        stat[i] = 0;
    }
    
    for(i = 0; i < numsSize; i++)
    {
        while(nums[i] != 0)
        {
            res = lowbit(nums[i]);
            nums[i] = nums[i] - res;
            res = log2((unsigned)res);
            stat[res]++;
        }
    }
    res = numsSize / 2;
    for(i = 0; i < 32; i++)
    {
        printf("%d  ",stat[i]);
        if(stat[i] > res)
        {
            ans += mypow(i);
        }
    }
    return ans;
}
不过思路倒是蛮正确的,结果在代码实现的时候不停的犯错,以后要注意要注意:1.对lowbit的使用还不熟悉;2.由题中说的majority element出现次数大于n/2,所以最后for循环中的条件判断一定是严格大于res。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值