您的位置:首页 > 其它

[Leetcode] 50, 55, 45

2017-09-01 15:21 211 查看

50. Pow(x, n)

Implement
pow(x, n).

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
4000
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;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: