Skip to content

Commit

Permalink
Jump game
Browse files Browse the repository at this point in the history
Signed-off-by: begeekmyfriend <[email protected]>
  • Loading branch information
begeekmyfriend committed Aug 2, 2017
1 parent 6567568 commit ac48b8a
Show file tree
Hide file tree
Showing 4 changed files with 75 additions and 0 deletions.
2 changes: 2 additions & 0 deletions 045_jump_game_ii/Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
all:
gcc -O2 -o test jump_game.c
37 changes: 37 additions & 0 deletions 045_jump_game_ii/jump_game.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
#include <stdio.h>
#include <stdlib.h>

static int jump(int* nums, int numsSize) {
if (numsSize <= 1) {
return 0;
}

int i;
int pos = numsSize - 1;
int *indexes = malloc(numsSize * sizeof(int));
int *p = indexes;

*p++ = numsSize - 1;
while (--pos >= 0) {
for (i = 0; i < p - indexes; i++) {
if (nums[pos] >= indexes[i] - pos) {
indexes[i + 1] = pos;
p = indexes + i + 2;
break;
}
}
}

return p - indexes - 1;
}

int main(int argc, char **argv)
{
int i, count = argc - 1;
int *nums = malloc(count * sizeof(int));
for (i = 0; i < count; i++) {
nums[i] = atoi(argv[i + 1]);
}
printf("%d\n", jump(nums, count));
return 0;
}
2 changes: 2 additions & 0 deletions 055_jump_game/Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
all:
gcc -O2 -o test jump_game.c
34 changes: 34 additions & 0 deletions 055_jump_game/jump_game.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

static bool canJump(int* nums, int numsSize) {
if (numsSize == 0) return false;

int i = numsSize - 1, j;
while (i > 0) {
if (nums[--i] == 0) {
for (j = i - 1; j >= 0; j--) {
if (nums[j] > i - j) {
break;
}
}
if (j == -1) {
return false;
}
}
}

return true;
}

int main(int argc, char **argv)
{
int i, count = argc - 1;
int *nums = malloc(count * sizeof(int));
for (i = 0; i < count; i++) {
nums[i] = atoi(argv[i + 1]);
}
printf("%s\n", canJump(nums, count) ? "true" : "false");
return 0;
}

0 comments on commit ac48b8a

Please sign in to comment.