Problems

经典题目

29 Divide Two Integers arrow-up-right

For example, dividend = 15, divisor = 2

Each time, we try to remove k(max) times of divisor(2) from dividend(15), where k * divisor <= dividend.

First time, 15 - divisor 2 2 = 7

Then, 7 - divisor * 2 = 3

Then, 3 - divisor = 1

public int divide(int dividend, int divisor) {
    // corner case
    if (dividend == Integer.MIN_VALUE && divisor == -1) return Integer.MAX_VALUE;
    if (dividend == 0) return 0;
    boolean isPos = ((dividend > 0 && divisor > 0) || (dividend < 0 && divisor < 0)) ? true : false;
    int res = 0;
    long dvd = Math.abs((long) dividend);
    long dvs = Math.abs((long) divisor);
    while (dvs <= dvd) {
        long tmp = dvs, multiple = 1;
        while (dvd >= (tmp << 1)) {
            tmp <<= 1;
            multiple <<= 1;
        }
        dvd -= tmp;
        res += multiple;
    }
    return isPos ? res : -res;
}

31 Next Permutation arrow-up-right

First, we observe that for any given sequence that is in descending order, no next larger permutation is possible.

We need to find the first pair of two successive numbers a[i] and a[i - 1], from the right, which satisfy a[i] > a[i - 1]. Now, all numbers to the right of a[i - 1] are in descending order, which means no larger permutations is possible for that sequence. So we need to increment a[i - 1] and we need to pick one number from a[i] to a[nums.length - 1] to replace with a[i - 1]. That would be the first number greater than a[i - 1] from the right. Then after the replacement, all the numbers to the right of a[i - 1] still remain descending. So finally, we need to reverse all the numbers from a[i] to a[nums.length - 1].

43 Multiply Strings arrow-up-right

num[i] * num[j] will be placed at indices i + j and i + j + 1

149 Max Points on a Line arrow-up-right

首先,两点确定一条直线。如果用斜率,则需要一个点和一个斜率。

所以,我们可以先确定一个点,再找另一个点,看在同一直直线上有多少个点。

需要注意的是,1. 相同的点的时候,即 same X && same Y。2. 直线斜率不存在的时候,即 same Y。3. 一般情况。

166 Fraction to Recurring Decimal arrow-up-right

  1. 处理无理数时,keep 一个 hashmap,防止出现无限循环小数

  2. 处理overflow时,比如-2147483648 / -1,-1 / -2147483648,转换成Long类型

172 Factorial Trailing Zeroes arrow-up-right

Because all trailing zeroes are from factors 2 * 5. We just need to count how many 5s out there. But some number have multiple 5s, like 25 have 2, and 125 have 3, etc.

204 Count Primesarrow-up-right

Mark all the evens, multiples of 3, multiples of 5, etc. as true. Then just count how many false are there.

592 Fraction Addition and Subtractionarrow-up-right

Last updated