Fast Power, LintCode

Calculate the an % b where a, b and n are all 32bit integers.

Example
For 231 % 3 = 2

For 1001000 % 1000 = 0

Challenge
O(logn)

数学问题,要求O(log n)的时间复杂度,也就是每次去掉一半的计算量,先要找到对应的数学公式:
(a * b) % p = (a % p * b % p) % p

所以(a^n)%b = (a^n/2 * a^n/2 * a) % b = ((a^n/2 * a^n/2)%b * a%b) % b
注意int和long的转化,防止溢出。

class Solution {
    /*
     * @param a, b, n: 32bit integers
     * @return: An integer
     */
    public int fastPower(int a, int b, int n) {
        // write your code here
        long ret = getPower(a, b, n);
        return (int)ret;
    }
    public long getPower(int a, int b, int n){
        if(a == 0) return 0;
        if(n == 0) return 1 % b;
        if(n == 1) return a % b;
        
        long ret = getPower(a, b, n/2);
        ret *= ret;
        ret %= b;
        if(n % 2 == 1){
            ret = ret * (a % b);
        }
        return ret % b;
    }
};
Advertisements

Binary Search Duplicated Values

Binary search is easy, but what if there are duplicated elements in the sorted array and you need to find the first index of the target value?

class Solution {
    /**
     * @param nums: The integer array.
     * @param target: Target to find.
     * @return: The first position of target. Position starts from 0.
     */
    public int binarySearch(int[] nums, int target) {
        //write your code here
        int left = 0;
        int right = nums.length-1;
        int mid = 0;
        int result = -1;
        while(left < right){
            mid = left + (right - left) / 2;
            if(nums[mid] == target){
                result = mid;
                right = mid;
            }
            else if(nums[mid] > target){
                right = mid;
            }
            else{
                left = mid + 1;
            }
        }
        return result;
    }
}

A + B Problem, LintCode 解题笔记

For given numbers a and b in function aplusb, return the sum of them.

Note
You don’t need to parse the input and output. Just calculate and return.

Example
If a=1 and b=2 return 3

Challenge
Can you do it with out + operation?

Clarification
Are a and b both 32-bit integers?
– Yes.

位运算实现整数加法本质就是用二进制进行运算。
其主要用了两个基本表达式:
x^y //执行加法,不考虑进位。
(x&y)<<1 //进位操作
令x=x^y ;y=(x&y)<<1 进行迭代,每迭代一次进位操作右面就多一位0,最多需要“加数二进制位长度”次迭代就没有进位了,此时x^y的值就是结果。

我们来做个3位数的加法:
101+011=1000 //正常加法
位运算加法:
(1) 101 ^ 011 = 110
(101 & 011)<<1 = 010
(2) 110 ^ 010 = 100
(110 & 010)<<1 = 100
(3) 100 ^ 100 = 000
(100 & 100)<<1 = 1000
此时进行相加操作就没有进位了,即000 ^ 1000=1000即是最后结果。

class Solution {
    /*
     * param a: The first integer
     * param b: The second integer
     * return: The sum of a and b
     */
    public int aplusb(int a, int b) {
        while(b != 0){
            int carry = a & b;
            a = a ^ b;
            b = carry << 1;
        }
        return a;
    }
}