例题

1. 丑数

描述
image.png
思路
三指针,指向最小值的向前移动。
代码
Python代码:

  1. class Solution:
  2. def nthUglyNumber(self, n: int) -> int:
  3. q = [1]
  4. i, j, k = 0, 0, 0
  5. for _ in range(n-1):
  6. t = min(q[i] * 2, q[j] * 3, q[k] * 5)
  7. q.append(t)
  8. if q[i] * 2 == t:
  9. i += 1
  10. if q[j] * 3 == t:
  11. j += 1
  12. if q[k] * 5 == t:
  13. k += 1
  14. return q[-1]

c++代码:

  1. class Solution {
  2. public:
  3. int nthUglyNumber(int n) {
  4. vector<int> q(1, 1);
  5. int i=0, j=0, k = 0;
  6. while (-- n) {
  7. int t = min(q[i] * 2, min(q[j] * 3, q[k] * 5));
  8. q.push_back(t);
  9. if (t == q[i] * 2) i++;
  10. if (t == q[j] * 3) j++;
  11. if (t == q[k] * 5) k++;
  12. }
  13. return q.back();
  14. }
  15. };

Java代码:

  1. class Solution {
  2. public int nthUglyNumber(int n) {
  3. List<Integer> q = new ArrayList<>();
  4. q.add(1);
  5. int i = 0, j = 0, k = 0;
  6. while (n > 1) {
  7. int t = Math.min(q.get(i) * 2, Math.min(q.get(j)* 3, q.get(k) * 5));
  8. q.add(t);
  9. if (q.get(i) * 2 == t) i++;
  10. if (q.get(j) * 3 == t) j++;
  11. if (q.get(k) * 5 == t) k++;
  12. n--;
  13. }
  14. return q.get(q.size() - 1);
  15. }
  16. }

2. 最大公约数

C++代码:

int gcd(int a, int b)
{
    return b ? gcd(b, a % b) : a;
}

Java代码:

public static int gcd(int a, int b) {
        return b > 0? gcd(b, a % b) : a;
    }

Python代码:

def gcd(a, b):
    return gcd(b, a % b) if b else a

3. 最小公倍数

Java代码:

public static int gcd(int a, int b) {
        return b > 0? gcd(b, a % b) : a;
    }
public static int lcm(int a , int b) {
    return a * b / gcd(a, b);
}

Python代码:

def gcd(a, b):
    return gcd(b, a % b) if b else a


def lcm(a, b):
    return a * b // gcd(a, b)

4. 判断质数

Python代码:

def is_prime(a):
    if a < 2:
        return False
    for i in range(2, a // 2 + 1):
        if a % i == 0:
            return False
    return True

Java代码:

public static boolean isPrime(int a) {
        if (a < 2) return false;
        for (int i = 2; i < a / 2 + 1; i++) {
            if (a % i == 0) return false;
        }
        return true;
    }

5. 判断闰年

Python代码:

def is_leap(year):
    if year % 4 == 0 and year % 100 != 0 or year % 400 == 0:
        return True
    return False

6. 快速幂

c++代码:

// 求 m^k mod p,时间复杂度 O(logk)。

int qmi(int m, int k, int p)
{
    int res = 1 % p, t = m;
    while (k)
    {
        if (k&1) res = res * t % p;
        t = t * t % p;
        k >>= 1;
    }
    return res;
}

Java代码:

public static int mul(int m, int k, int p) {
        int res = 1 % p;
        while (k > 0) {
            if ((k & 1) == 1) {
                res = res * m % p;
            }
            m = m * m % p;
            k >>= 1;
        }
        return res;
    }

Python代码:

def mul(m, k, p):
    res = 1 % p
    t = m
    while k:
        if k & 1:
            res = res * t % p
        t = t * t % p
        k >>= 1
    return res