[Leetcode] 50, 55, 45

50. Pow(x, n)

Implement pow(xn).

Solution:分治法,注意n有可能是负数的情况。

Code:

class Solution {
public:
    double myPow(double x, int n) {
        if(n==0) return 1;
        if(n==1) return x;
        if(n==-1) return 1/x;
        double single = pow(x, n%2);
        double ans = myPow(x, n/2);
        ans = ans*single*ans;
        return ans;
    }
};




55. Jump Game

Given an array of non-negative integers, you are initially positioned at the first index of the array.

Each element in the array represents your maximum jump length at that position.

Determine if you are able to reach the last index.

For example:
A = [2,3,1,1,4], return true.

A = [3,2,1,0,4], return false.

Solution: 贪心,对于当前可以抵达的每一层计算一下是否可以扩展最远可抵达结点,如果最终的可抵达结点可以到达最后一个节点则返回true,否则为false。

Code:

class Solution {
public:
    bool canJump(vector<int>& nums) {
        int MAX = 0;
        for(int i=0; i<=MAX && MAX<nums.size()-1; i++){
            MAX = max(MAX, i + nums[i]);
        }
        return MAX>=nums.size()-1;
    }
};



45. Jump Game II

Given an array of non-negative integers, you are initially positioned at the first index of the array.

Each element in the array represents your maximum jump length at that position.

Your goal is to reach the last index in the minimum number of jumps.

For example:
Given array A = [2,3,1,1,4]

The minimum number of jumps to reach the last index is 2. (Jump 1 step from index 0 to 1, then 3 steps to the last index.)

Note:
You can assume that you can always reach the last index.

Solution: 贪心,对于每一个到达的index,在它能到达的index中,将通过它能更新为更小步数的index更新。但是直接这样写会超时,因为这中访问方式有一个特点,index较小的点访问下一个节点得到的步数一定小于等于index大的点访问同一个节点(易得,因为如果能通过步数x访问index,那么一定最多通过x访问index-1),因此最先访问的步数一定是最小步数,所以不需要循环那么多次。

Code(1):

class Solution {
public:
    int jump(vector<int>& nums) {
        vector<int> steps(nums.size(), INT_MAX);
        steps[0] = 0;
        int MIN = 1;
        for(int i=0; i<nums.size(); i++){
            for(int t=MIN; t<=i+nums[i] && t<steps.size(); t++){
                if(steps[t]>steps[i]){
                    steps[t] = steps[i]+1;
                    MIN = max(t+1, MIN);
                }
            }
        }
        return steps.back();
    }
};

Code(2): 将上面的代码稍作改进,实际上不需要O(n)的空间,只需要O(1)就足够了。

class Solution {
public:
    int jump(vector<int>& nums) {
        int steps = 0;
        int left = 0;
        int right = 1;
        //到达[left, right)所需的步数是steps
        while(left<right && right<nums.size()){
            int end = right;
            for(int i=left; i<end; i++)
                right = max(right, i+nums[i]+1);
            left = end;
            steps++;
        }
        return steps;
    }
};



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值