From e39d469ab579dcfd2a25b630cdc70f032be6c169 Mon Sep 17 00:00:00 2001 From: Leo Ma Date: Sat, 29 Jul 2017 08:51:57 +0800 Subject: [PATCH] Jump game Signed-off-by: Leo Ma --- .../valid_parentheses.c | 2 + 045_jump_game/Makefile | 2 + 045_jump_game/jump_game.c | 38 +++++++++++++++++++ 3 files changed, 42 insertions(+) create mode 100644 045_jump_game/Makefile create mode 100644 045_jump_game/jump_game.c diff --git a/032_longest_valid_parentheses/valid_parentheses.c b/032_longest_valid_parentheses/valid_parentheses.c index 2dc0860..525c186 100644 --- a/032_longest_valid_parentheses/valid_parentheses.c +++ b/032_longest_valid_parentheses/valid_parentheses.c @@ -18,8 +18,10 @@ static int longestValidParentheses(char* s) { } else { if (top > stack) { if (--top == stack) { + /* The stack never keep ')' so we use 'error' to record index */ length = s - p - error; } else { + /* The *(top - 1) is the index of the last kept '(' */ length = s - p - *(top - 1); } if (length > max_length) { diff --git a/045_jump_game/Makefile b/045_jump_game/Makefile new file mode 100644 index 0000000..e39cccc --- /dev/null +++ b/045_jump_game/Makefile @@ -0,0 +1,2 @@ +all: + gcc -O2 -o test jump_game.c diff --git a/045_jump_game/jump_game.c b/045_jump_game/jump_game.c new file mode 100644 index 0000000..ce7a807 --- /dev/null +++ b/045_jump_game/jump_game.c @@ -0,0 +1,38 @@ +#include +#include + +static int jump(int* nums, int numsSize) { + if (numsSize <= 1) { + return 0; + } + + int i; + int next_pos = numsSize - 1; + int pos = next_pos; + 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; +}