diff --git a/045_jump_game_ii/Makefile b/045_jump_game_ii/Makefile new file mode 100644 index 0000000..e39cccc --- /dev/null +++ b/045_jump_game_ii/Makefile @@ -0,0 +1,2 @@ +all: + gcc -O2 -o test jump_game.c diff --git a/045_jump_game_ii/jump_game.c b/045_jump_game_ii/jump_game.c new file mode 100644 index 0000000..53a8128 --- /dev/null +++ b/045_jump_game_ii/jump_game.c @@ -0,0 +1,37 @@ +#include +#include + +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; +} diff --git a/055_jump_game/Makefile b/055_jump_game/Makefile new file mode 100644 index 0000000..e39cccc --- /dev/null +++ b/055_jump_game/Makefile @@ -0,0 +1,2 @@ +all: + gcc -O2 -o test jump_game.c diff --git a/055_jump_game/jump_game.c b/055_jump_game/jump_game.c new file mode 100644 index 0000000..8d4e5b0 --- /dev/null +++ b/055_jump_game/jump_game.c @@ -0,0 +1,34 @@ +#include +#include +#include + +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; +}