-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0055-JumpGame.cs
91 lines (84 loc) · 2.24 KB
/
0055-JumpGame.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
using System;
using Xunit;
using Util;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;
using System.IO;
namespace JumpGame
{
public class Solution
{
public bool CanJump(int[] nums)
{
if (nums.Length == 1)
return true;
// find jump point from last one to first
// the previous jump point must be the most left one meet "nums[idx] >= distance" to next jump point
var idx = nums.Length - 1;
var steps = 0;
bool canJump = false;
while (true)
{
if (idx <= 0)
{
break;
}
canJump = false;
for (var i = 0; i < idx; i++)
{
var x = nums[i];
var dist = idx - i;
if (x >= dist)
{
canJump = true;
steps++;
if (i == 0)
{
return canJump;
}
idx = i;
break;
}
}
if (!canJump)
{
return false;
}
}
return canJump;
}
}
public class Test
{
static void Verify(int[] nums, bool exp)
{
Console.WriteLine($"{string.Join(',', nums)}");
bool res;
using (new Timeit())
{
res = new Solution().CanJump(nums);
}
Assert.Equal(exp, res);
}
static public void Run()
{
Console.WriteLine("JumpGame");
int[] nums;
bool exp;
nums = new int[] { 2, 3, 1, 1, 4 };
exp = true;
Verify(nums, exp);
nums = new int[] { 3, 2, 1, 0, 4 };
exp = false;
Verify(nums, exp);
nums = new int[] { 0 };
exp = true;
Verify(nums, exp);
nums = new int[] { 1 };
exp = true;
Verify(nums, exp);
}
}
}