「算法」数学和位运算

single number

Question

    lintcode: (82) Single Number

Given 2*n + 1 numbers, every numbers occurs twice except one, find it.

Example
Given [1,2,2,1,3,4,3], return 4

Challenge
One-pass, constant extra space

x xor x==0x xor 0==x
且异或(位运算)操作具有可交换性,所以用第一个元素与之后所有元素异或,得到的最终结果就是single元素。

class Solution {
public:
    /**
     * @param A: Array of integers.
     * return: The single number.
     */
    int singleNumber(vector<int> &A) {
        // write your code here
        if(A.empty())return 0;
        for(int i =1;i<A.size();i++){
            A[0]=A[0]^A[i];
        }
        return A[0];
    }
};

single number II

Problem Statement

Given 3*n + 1 numbers, every numbers occurs triple times except one, find

it.
Example

Given [1,1,2,3,3,3,2,2,4,1] return 4
Challenge

One-pass, constant extra space.

题解1 - 逐位处理
对于三个相同的数来说,其相加的和必然是3的倍数,仅仅使用这一个特性还不足以将单数找出来,我们再来挖掘隐含的信息。
三个相同的数相加,不仅其和能被3整除,其二进制位上的每一位也能被3整除!因此我们只需要一个和int类型相同大小的数组记录每一位累加的结果即可。时间复杂度约为 O((3n+1)sizeof(int)8)

class Solution {
public:
    int singleNumber(vector<int>& nums) {
        if(nums.empty()||nums.size()<=1)return nums[0];
        //int * r=new int(sizeof(int)*8);
        //memset(r,0,32);
        //int r[sizeof(int)*8]={0};
        //vector<int> r(sizeof(int)*8);
        // for(int j=0;j<sizeof(int)*8;j++)
        // {
        //     r[j]=0;
        //     for(int i=0;i<nums.size();i++)
        //     {
        //         r[j]+=nums[i]&1;
        //         nums[i]>>1;
        //     }
        //     r[j]=r[j]%3;
        // }
        // int rtn=0;
        // for(int k=sizeof(int)*8-1;k>=0;k++)
        //     {
        //         rtn+=r[k];
        //         rtn<<1;
        //     }
        int r=0;
        for(int i=0;i<sizeof(int)*8;++i)
        {
            int bitNum=0;
            for(int j=0;j<nums.size();j++)
            {
                bitNum+=(nums[j]>>i)&1;
            }
            r|=(bitNum%3)<<i;
        }
        return r;
    }
};

注意:移位操作” >> ”是否会改变原来的数?? >>

Single Number III //还没搞明白-_-|||

Question

    lintcode: (84) Single Number III

Given 2*n + 2 numbers, every numbers occurs twice except two, find them.

Example
Given [1,2,2,3,4,4,5,3] return 1 and 5

Challenge
O(n) time, O(1) extra space.

关键点:将大数组拆分乘两个小数组,两个数组中分别包含一个单独数字,其他数字仍然成对存在。
按照single number I 中的方法,全部异或之后得到的是两个单独数的异或结果,由于两个数不同,所以至少有一位为1,我们通过操作a1=a&(a-1)^a可以得到最低位的1(或者通过啊a&(-a)得到最高位的1//why???),这个数只有该位为1,其他位为0,通过这个数与数组中的每个数与的结果,将数组分为两个小数组(关键),这两个数组中分别包含了一个single number,其他的数仍是成对存在的(想原因),再分别对两个数组进行single number I中的操作。

class Solution {
public:
    /**
     * @param A : An integer array
     * @return : Two integers
     */
    vector<int> singleNumberIII(vector<int> &nums) {
        // write your code here
        if(nums.empty()||nums.size()<=2)return nums;
        int a=nums[0];
        for(int i=1;i<nums.size();i++){
            a^=nums[i];
        }
        vector<int> nums1,nums2;
        int a1=a&(a-1)^a;//关键,如何得到最低/最高位的1
        for(int j=0;j<nums.size();j++){
            if(nums[j]&a1)nums1.push_back(nums[j]);
            else nums2.push_back(nums[j]);
        }
        vector<int> result;
        int r;
        if(nums1.size()==1)result.push_back(nums1[0]);
        else{
            r=nums1[0];
            for(int k=1;k<nums1.size();k++){
                r^=nums1[k];
                }
            result.push_back(r);
        }
        if(nums2.size()==1)result.push_back(nums2[0]);
        else{
            r=nums2[0];
            for(int k=1;k<nums2.size();k++){
                r^=nums2[k];
            }
            result.push_back(r);
        }
        return result;
    }
};
//九章算数给出的程序,比我的简洁很多
/**
 * 本代码由九章算法编辑提供。版权所有,转发请注明出处。
 * - 九章算法致力于帮助更多中国人找到好的工作,教师团队均来自硅谷和国内的一线大公司在职工程师。
 * - 现有的面试培训课程包括:九章算法班,系统设计班,算法强化班,Java入门与基础算法班,Android 项目实战班,Big Data 项目实战班,
 * - 更多详情请见官方网站:http://www.jiuzhang.com/?source=code
 */

class Solution {
public:
    /**
     * @param A : An integer array
     * @return : two integers
     */
    vector<int> singleNumberIII(vector<int> &A) {
        // write your code here
        int x = 0, len = A.size(), pos;
        for (int i = 0; i < len; ++i)
            x ^= A[i];
        for (int i = 0; i < 32; ++i)
            if (x & (1 << i)) {
                pos = i;    
                break;            
            }
        vector<int> results(2);
        for (int i = 0; i < len; ++i)
        if (A[i] & (1 << pos))
            results[0] ^= A[i];
        else
            results[1] ^= A[i];
        return results;
    }
};

O(1) Check Power of 2

Question

    lintcode: (142) O(1) Check Power of 2

Using O(1) time to check whether an integer n is a power of 2.

Example
For n=4, return true;

For n=5, return false;

Challenge
O(1) time

运用之前的求二进制数中的1的个数的方法,个数为1个的是2的乘方数,注意输入定义域为0,+,-,0和负数都不是,return false;另外注意,三目运算符的优先级大于&,所以要加上括号;

class Solution {
public:
    /*
     * @param n: An integer
     * @return: True or false
     */
    bool checkPowerOf2(int n) {
        // write your code here
        if(n==0)return false;
        int num=n;
        if(n<0)return false;
        return (num&(num-1))==0?1:0;//三目运算符的优先级大于&,所以要加上括号;
    }
};

Convert Integer A to Integer B

A^B然后统计1的位数,用x=x & (x-1),直到x为0;

class Solution {
public:
    /**
     *@param a, b: Two integer
     *return: An integer
     */
    int bitSwapRequired(int a, int b) {
        int count = 0;
        int a_xor_b = a ^ b;
        while (a_xor_b != 0) {
            ++count;
            a_xor_b &= (a_xor_b - 1);
        }

        return count;
    }
};

Factorial Trailing Zeroes//暂时没想明白

Unique Binary Search Tree

Question

leetcode: Unique Binary Search Trees | LeetCode OJ
lintcode: (163) Unique Binary Search Trees
Given n, how many structurally unique BSTs (binary search trees)
that store values 1...n?

Example
Given n = 3, there are a total of 5 unique BST's.

1           3    3       2      1
 \         /    /       / \      \
  3      2     1       1   3      2
 /      /       \                  \
2     1          2                  3

与数据结构和动态规划都有点关系。这这么一句话——『以i为根节点的树,其左子树由[0, i-1]构成, 其右子树由[i+1, n]构成。』这不就是 BST 的定义嘛!灵活运用下就能找到递推关系了。

容易想到这道题的动态规划状态为 count[n], count[n] 表示到正整数 i 为止的二叉搜索树个数。容易得到 count[1] = 1, 根节点为1,count[2] = 2, 根节点可为1或者2。那么 count[3] 的根节点自然可为1,2,3. 如果以1为根节点,那么根据 BST 的定义,2和3只可能位于根节点1的右边;如果以2为根节点,则1位于左子树,3位于右子树;如果以3为根节点,则1和2必位于3的左子树。

抽象一下,如果以 i 作为根节点,由基本的排列组合知识可知,其唯一 BST 个数为左子树的 BST 个数乘上右子树的 BST 个数。故对于 i 来说,其左子树由[0, i - 1]构成,唯一的 BST 个数为 count[i - 1], 右子树由[i + 1, n] 构成,其唯一的 BST 个数没有左子树直观,但是也有迹可循。对于两组有序数列「1, 2, 3] 和 [4, 5, 6]来说,
对于两组有序数列「1, 2, 3] 和 [4, 5, 6]来说,这两个有序数列分别组成的 BST 个数必然是一样的,因为 BST 的个数只与有序序列的大小有关,而与具体值没有关系。所以右子树的 BST 个数为 count[n - i],于是乎就得到了如下递推关系:

count[i]=j=0i1(count[j]count[ij1])

递推关系是可以不用递推来实现的,用循环依次得到count[0]~count[n],最后返回count[n]。

//写的递归形式的,time limit exceeded,因为有很多重复的计算,应该用动态规划方法逐个存储,用循环完成
class Solution {
public:
    int numTrees(int n) {
        if(n<=0)return 1;
        if(n==1)return 1;
        if(n==2)return 2;
        int res=0;
        for(int i= 1;i<=n;i++){
            res+=numTrees(i-1)*numTrees(n-i);
        }
        return res;
    }
};
//通过,用动态规划方法?
class Solution {
public:
    int numTrees(int n) {
        if(n<=0)return 1;
        if(n==1)return 1;
        if(n==2)return 2;
        vector<int> res(n+1);
        res[0]=1;
        for(int i= 1;i<=n;i++)
        for(int j=0;j<i;j++){
            res[i]+=res[j]*res[i-j-1];
        }
        return res[n];
    }
};

Hash Function

In data structure Hash, hash function is used to convert a string(or any other type) into an integer smaller than hash size and bigger or equal to zero. The objective of designing a hash function is to "hash" the key as unreasonable as possible. A good hash function can avoid collision as less as possible. A widely used hash function algorithm is using a magic number 33, consider any string as a 33 based big integer like follow:

hashcode("abcd") = (ascii(a) * 333 + ascii(b) * 332 + ascii(c) *33 + ascii(d)) % HASH_SIZE 

                              = (97* 333 + 98 * 332 + 99 * 33 +100) % HASH_SIZE

                              = 3595978 % HASH_SIZE

here HASH_SIZE is the capacity of the hash table (you can assume a hash table is like an array with index 0 ~ HASH_SIZE-1).

Given a string as a key and the size of hash table, return the hash value of this key.f



Have you met this question in a real interview? Yes
Clarification
For this problem, you are not necessary to design your own hash algorithm or consider any collision issue, you just need to implement the algorithm as described.

Example
For key="abcd" and size=100, return 78

题目是在考察针对大数据的溢出问题,在字符串较长时,33的乘方很快溢出,因此要防止一处:

题解一:关键在于一个公式: ab%m=a%mb%m 求余;
//时间复杂度O(n),空间复杂度O(1);
class Solution {
public:
    /**
     * @param key: A String you should hash
     * @param HASH_SIZE: An integer
     * @return an integer
     */
    int hashCode(string key,int HASH_SIZE) {
        // write your code here
        int l=key.length();
        long int res=0;
        for(int i=0;i<l;i++)
        {
            res=res*33+key[i];
            res%=HASH_SIZE;
        }
        return res;
    }
};
题解二:另外有一个对乘方运算进行二分法优化的算法,关键也在于公式: ab%m=a%mb%m

Count 1 in Binary

Question
Count how many 1 in binary representation of a 32-bit integer.

Example
Given 32, return 1

Given 5, return 2

Given 1023, return 9

Challenge
If the integer is n bits with m 1 bits. Can you do it in O(m) time?

x&=x-1将x的最后一个1变为0,until x==0,可以得到1的个数;

Fibonacci

Question

Problem Statement

Find the _N_th number in Fibonacci sequence.

A Fibonacci sequence is defined as follow:

    The first two numbers are 0 and 1.
    The i th number is the sum of i-1 th number and i-2 th number.

The first ten numbers in Fibonacci sequence is:

0, 1, 1, 2, 3, 5, 8, 13, 21, 34 ...
Example

Given 1, return 0

Given 2, return 1

Given 10, return 34
Note

The _N_th fibonacci number won't exceed the max value of signed 32-bit integer

in the test cases.

虽然是很初级的题目,但是要考虑到复杂度,溢出,计算效率等,最好使用循环方式,从头开始将计算得到的结果储存留到之后使用。

class Solution{
public:
    /**
     * @param n: an integer
     * @return an integer f(n)
     */
    int fibonacci(int n) {
        // write your code here
        if(n==0)return 0;
        if(n==1)return 1;
        vector<int> f(n);
        f[0]=0;
        f[1]=1;
        int i=2;
        while(i<=n)
        {
            f[i]=f[i-1]+f[i-2];
            i++;
        }
        return f[n-1];
    }
};

A plus B Problem

Question

    lintcode: (1) A + B Problem

Write a function that add two numbers A and B.
You should not use + or any arithmetic operators.


Example
Given a=1 and b=2 return 3

Note
There is no need to read data from standard input stream.
Both parameters are given in function aplusb,
you job is to calculate the sum and return it.
Challenge
Of course you can just return a + b to get accepted.
But Can you challenge not do it like that?
Clarification
Are a and b both 32-bit integers?
Yes.
Can I use bit operation?

Sure you can.

利用递归,求&后右移一位是进位,求或是部分位的球和结果,将进位和部分位求和结果递归带入求和函数,直到进位为0时递归结束;

class Solution {
public:
    /*
     * @param a: The first integer
     * @param b: The second integer
     * @return: The sum of a and b
     */
    int aplusb(int a, int b) {
        // write your code here, try to do it without arithmetic operators.
        int yu=a&b;
        yu=yu<<1;
        int yihuo=a^b;
        if(yu!=0)
        {
            yihuo=aplusb(yu,yihuo);
        }
        return yihuo;
    }
};
Question
Print numbers from 1 to the largest number with N digits by recursion.

Example
Given N = 1, return [1,2,3,4,5,6,7,8,9].

Given N = 2, return [1,2,3,4,5,6,7,8,9,10,11,12,...,99].

Note
It's pretty easy to do recursion like:

recursion(i) {
    if i > largest number:
        return
    results.add(i)
    recursion(i + 1)
}
however this cost a lot of recursion memory as the recursion depth maybe very large.
Can you do it in another way to recursive with at most N depth?

Challenge
Do it in recursion, not for-loop.

同样是递归的思想,将先计算好的结果记录下来,每次大循环十次,将之前返回的数组扩容至十倍,注意边界处10,20等的处理,注意size不能用res.size()代替,因为一直在变;时间复杂度 O(10n) ,空间复杂度 O(1) (此处存疑,空间复杂度指的是除去返回结果之外需要的额外空间大小?如果是总的空间大小,那么应为 O(10n) )。

class Solution {
public:
    /**
     * @param n: An integer.
     * return : An array storing 1 to the largest number with n digits.
     */
    vector<int> numbersByRecursion(int n) {
        // write your code here
        if(n==0)return {};
        if(n==1)return {1,2,3,4,5,6,7,8,9};
        vector<int> res=numbersByRecursion(n-1);
        int size=res.size();//in the next lines, the size of res will be changed ,so we must store the //original size we want.
        for(int i=1;i<10;++i)
        {
            res.push_back(i*pow(10,n-1));
            for(int j=0;j<size;++j)
            {
                res.push_back(i*pow(10,n-1)+res[j]);
            }
        }
        return res;
    }
};

Majority Number

Question

    leetcode: Majority Element | LeetCode OJ
    lintcode: (46) Majority Number

Given an array of integers, the majority number is
the number that occurs more than half of the size of the array. Find it.

Example
Given [1, 1, 1, 1, 2, 2, 2], return 1

Challenge
O(n) time and O(1) extra space

最简单的想法:hashmap统计所有,找出次数大于的,时间复杂度 O(n)
另一种思路:利用快速排序思想,找到中位数;
另一种思路:既然某个数超过二分之一,那么用这个数和其他数进行 PK,不同的计数器都减一(核心在于两两抵消),相同的则加1,最后返回计数器大于0的即可。

//目前并没有完全搞懂这种思路的内涵是在哪里


//第三种思路:
int majorityNumber(vector<int> nums) {
    if (nums.empty()) return -1;

    int k = -1, count = 0;
    for (auto n : nums) {
        if (!count) k = n;
        if (k == n) count++;
        else count--;
    }
    return k;
}

Majority Number III

Question
Given an array of integers and a number k,
the majority number is the number that occurs more than 1/k of the size of the array.

Find it.

Example
Given [3,1,2,3,2,3,3,4,4,4] and k=3, return 3.

Note
There is only one majority number in the array.

Challenge
O(n) time and O(k) extra space

//同上,目前没搞清思路是什么道理

Digit Counts

Question

    leetcode: Number of Digit One | LeetCode OJ
    lintcode: (3) Digit Counts

Count the number of k's between 0 and n. k can be 0 - 9.

Example
if n=12, k=1 in [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],
we have FIVE 1's (1, 10, 11, 12)

题解1:利用字符串处理数字问题,to_string(int)将int转化为string,注意c++11的新用法:但是这种方法会TLE,考虑题解2?我想出来的大概是迭代法,等待实践。

**基于范围的for循环**
for(auto s:sstring){};

C++11提供了关于for循环的新特性:基于范围的for循环( the range-base for statement),再加上”类型推导”特性可以将上面的代码进一步简化:

//&的用法??

for(auto &node:lst){
    cout<<node<<endl;
    //do something
}
for(auto s:to_string(i))//可能是针对有迭代器的类型,对其中元素进行遍历

题解

class Solution {
public:
    /*
     * param k : As description.
     * param n : As description.
     * return: How many k's between 0 and n.
     */
    int digitCounts(int k, int n) {
        // write your code here
        if(k>9||k>n)return 0;
        if(n<0)return 0;
        int result=0;
        const char ck=k+'0';
        for(int i =0;i<=n;++i){
            string sn=to_string(i);//the string.size() include the '\0'??
            for(int j=0;j<sn.size();++j){
                if(ck==sn[j])result++;
            }
            // for(auto s:to_string(i))
            // if(s==ck)result++;
        }
        return result;
    }
};

题解二

//尚未解决

 //to be write with recursion

Ugly Number

Question
    leetcode: Ugly Number | LeetCode OJ
    lintcode: (4) Ugly Number

Ugly number is a number that only have factors 3, 5 and 7.

Design an algorithm to find the Kth ugly number.
The first 5 ugly numbers are 3, 5, 7, 9, 15 ...
Example
If K=4, return 9.
Challenge
O(K log K) or O(K) time.

尝试使用hashmap或者set来以空间换取时间,结果还是TLE

\\TLE
class Solution {
public:
    int nthUglyNumber(int n) {
        if(n==1)return 1;
        // map<int,bool> sUgly;
        // sUgly[1]=true;
        set<int> sUgly;
        sUgly.insert(1);
        int ind=1;
        int num=2;
        int res=1;
        while(ind<n)
        {
            if((num%2==0&&(sUgly.find(num/2)!=sUgly.end()))
            ||(num%3==0&&(sUgly.find(num/3)!=sUgly.end()))
            ||(num%5==0&&(sUgly.find(num/5)!=sUgly.end()))
            )
            {
                ++ind;
                sUgly.insert(num);
                //sUgly[num]=true;
                res=num;
            }
            ++num;
        }
        return res;
    }
};

新写了一段复杂度很高的代码,结果通过了,没有高深的理论,而是用蛮力,注意数据容量要大,用longlong,另外注意各种逻辑关系。

class Solution 
{
public:
    int nthUglyNumber(int n) 
    {
        if(n==1)return 1;
        vector<long long> u(4);//ugly numbers//attention ,the number may be big ,so use longlong int.
        u[0]=2;
        u[1]=3;
        u[2]=4;
        u[3]=5;
        while(u.size()<n-1)
        {
            bool findABiggerNumber=false;
            long long int max=u[u.size()-1];
            long long int originMax=u[u.size()-1];
            for(int i =0;i<u.size();++i)
            {
                if(!findABiggerNumber)
                {
                    if(2*u[i]>max)
                    {
                        max=2*u[i];
                        findABiggerNumber=1;       
                    }
                    else if(3*u[i]>max)
                    {
                        max=3*u[i];
                        findABiggerNumber=1;
                    }
                    else if(5*u[i]>max)
                    {
                        max=5*u[i];
                        findABiggerNumber=1;
                }
                }
                else
                {
                        if( 2*u[i]>originMax && 2*u[i]<max)
                    {
                        max=2*u[i];
                    }
                    else if(3*u[i]>originMax && 3*u[i]<max )
                    {
                        max=3*u[i];
                    }
                    else if(5*u[i]>originMax && 5*u[i]<max )
                    {
                        max=5*u[i];
                    }
                }
            }
            u.push_back(max);
        }
        return u[n-2];
    }
};

在实验楼中提供的题解二中,提到了二分查找

题解2 - 二分查找

根据丑数的定义,它的质因数只含有3, 5, 7, 那么根据这一点其实可以知道后面的丑数一定可以从前面的丑数乘3,5,7得到。那么可不可以将其递推关系用数学公式表示出来呢?

我大概做了下尝试,首先根据丑数的定义可以写成 ¥¥Uk=3x3⋅5x5⋅7x7U_k = 3^{x_3} \cdot 5^{x_5} \cdot 7^{x_7}U​k​​=3​x​3​​​​⋅5​x​5​​​​⋅7​x​7​​​​, 那么 Uk+1U_{k+1}U​k+1​​ 和 UkU_kU​k​​ 的不同则在于 x3,x5,x7x_3, x_5, x_7x​3​​,x​5​​,x​7​​ 的不同,递推关系为 Uk+1=Uk⋅3y3⋅5y5⋅7y73z3⋅5z5⋅7z7U_{k+1} = U_k \cdot \frac{3^{y_3} \cdot 5^{y_5} \cdot 7^{y_7}}{3^{z_3} \cdot 5^{z_5} \cdot 7^{z_7}}U​k+1​​=U​k​​⋅​3​z​3​​​​⋅5​z​5​​​​⋅7​z​7​​​​​​3​y​3​​​​⋅5​y​5​​​​⋅7​y​7​​​​​​,将这些分数按照从小到大的顺序排列可在 $$O(K)$$ 的时间内解决,但是问题来了,得到这些具体的 y,zy, zy,z 就需要费不少时间,且人工操作极易漏解。:( 所以这种解法只具有数学意义,没有想到好的实现方法。

除了这种找相邻递推关系的方法我们还可以尝试对前面的丑数依次乘3, 5, 7,直至找到比当前最大的丑数大的一个数,对乘积后的三种不同结果取最小值即可得下一个最大的丑数。这种方法需要保存之前的 N 个丑数,由于已按顺序排好,天然的二分法。

对于提到的递归的方法,我也没有想到好的方法去得到递归表达式;
但对于之后提到的天然的二分搜索,我的理解是这样的,作者的意思是,将得到的前几个ugly numbers 每个都乘以2,3,5,并将×2,×3,×5的结果分别保存为数组,得到三个数组,由于之前的几个uglynumber是排序的,所以得到的这三个内部分别是排序的,在这三个中分别用二分搜索(换言之,二分查找的条件是数组已排序),再得到这三个结果中的较小的数来作为下一个ugly number。得到下一个ugly的时间复杂度为 O(logn+3×n) ,n为当前数组的数目,总的复杂度大概是估计是 O(N(N1)2n=Nn=1(logn+3n)/n) (我自己估算的,代验证),大概结果是 O(n2O(n3) 之间。实验楼中说复杂读在 O(logNN) ,哦是不理解了。
我的那种蛮力算法,并没有对查找方法进行优化,进行比较的次数会多一些,但是不需要额外的空间n来存储×2/3/5之后的结果,所以空间复杂度会低一些。

My 16ms C++ DP solution with short explanation

We have an array k of first n ugly number. We only know, at the beginning, the first one, which is 1. Then

k[1] = min( k[0]x2, k[0]x3, k[0]x5). The answer is k[0]x2. So we move 2's pointer to 1. Then we test:

k[2] = min( k[1]x2, k[0]x3, k[0]x5). And so on. Be careful about the cases such as 6, in which we need to forward both pointers of 2 and 3.

x here is multiplication.

class Solution {
public:
    int nthUglyNumber(int n) {
        if(n <= 0) return false; // get rid of corner cases 
        if(n == 1) return true; // base case
        int t2 = 0, t3 = 0, t5 = 0; //pointers for 2, 3, 5
        vector<int> k(n);
        k[0] = 1;
        for(int i  = 1; i < n ; i ++)
        {
            k[i] = min(k[t2]*2,min(k[t3]*3,k[t5]*5));
            if(k[i] == k[t2]*2) t2++; 
            if(k[i] == k[t3]*3) t3++;
            if(k[i] == k[t5]*5) t5++;
        }
        return k[n-1];
    }
};
题解3 - 动态规划

TBD
leetcode上的另一ugly有关的题目,带解决
super ugly number

Plus One

Question

    leetcode: Plus One | LeetCode OJ
    lintcode: (407) Plus One

Problem Statement

Given a non-negative number represented as an array of digits, plus one to the number.

The digits are stored such that the most significant digit is at the head of the list.
Example

Given [1,2,3] which represents 123, return [1,2,4].

Given [9,9,9] which represents 999, return [1,0,0,0].
题解

又是一道两个整数按数位相加的题,自后往前累加,处理下进位即可。这道题中是加1,其实还可以扩展至加2,加3等。
下面是自己写的程序:

class Solution {
public:
    int plus(int &d)
    {
        if(d==9)
        {
            d=0;
            return 1;
        }
        else
        {
            ++d;
            return 0;
        }
    }
    vector<int> plusOne(vector<int>& digits) {
        int i =plus(digits[digits.size()-1]);
        //int addUp=0;
        int j =digits.size()-2;
        while(i&&j>=0)
        {
            i=plus(digits[j]);
            --j;
        }
        if(i)digits.insert(digits.begin(),1);
        return digits;
    }
};

终于该下一话题了。。。链表,还是二分查找呢?

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值