简单算法题

2020-01-29  本文已影响0人  楼上那只猫

斐波那契数列

int fibe(int n) {
    if (n == 1 || n == 2) {
        return 1;
    } else {
        return fibe(n -1) + fibe(n - 2);
    }
}

判断一个数是否是质数(只能被1和本身整除)

int isPrime(int num) {
    for (int i = 2; i < num - 1; i++) {
        if (num % i == 0) {
            return 0;
        }
    }
    return 1;
}

判断是否是丑数
丑数就是只包含质因数 2, 3, 5 的正整数

int isUgly(int num) {
    if (num == 0) {
        return -1;
    } else if(num == 1) {
        return 1;
    } else {
        while (num % 2 == 0) {
            num /= 2;
        }
        while (num % 3 == 0) {
            num /= 3;
        }
        while (num % 5 == 0) {
            num /= 5;
        }
        if (num == 1) {
            return 1;
        }
        return -1;
    }
}

给定一个非空整数数组,除了某个元素只出现一次以外,其余每个元素均出现两次。找出那个只出现了一次的元素.
这里使用了异或运算符(^),该运算符的特性如下:假设有值甲、乙,当甲乙值相等时,异或操作后结果为不等(False,0),反之,为相等(True,1)。

按位异或操作的性质:一个值和0进行按位异或操作所得为该值,相同的两个值进行异或操作,所得为0(甲 按位异或 0 得 甲,甲 按位异或 甲 得 0)

由此可以知道,对于数组中重复的元素,进行异或操作后最终为0,那么,剩余的一个只出现一次的元素进行异或,得到的就是该元素。

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

众数
给定一个大小为 n 的数组,找到其中的多数元素。多数元素是指在数组中出现次数大于 ⌊ n/2 ⌋ 的元素。
你可以假设数组是非空的,并且给定的数组总是存在多数元素。
解法主要是用到了摩尔投票

int majorityElement(int* nums, int numsSize){
    int res = 0;
    int count = 0;
    for (int i = 0; i < numsSize; i++) {
        if (count == 0) {
            res = nums[i];
            count = 1;
        } else {
            if (res == nums[i]) {
                count++;
            } else {
                count--;
            }
        }
    }
    return res;
}
上一篇 下一篇

猜你喜欢

热点阅读