Skip to content

Commit

Permalink
Search for a range
Browse files Browse the repository at this point in the history
Signed-off-by: begeekmyfriend <[email protected]>
  • Loading branch information
begeekmyfriend committed Jul 25, 2017
1 parent 1579800 commit cee8800
Show file tree
Hide file tree
Showing 2 changed files with 76 additions and 0 deletions.
2 changes: 2 additions & 0 deletions 034_search_for_a_range/Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
all:
gcc -O2 -o test range_search.c
74 changes: 74 additions & 0 deletions 034_search_for_a_range/range_search.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
#include <stdio.h>
#include <stdlib.h>

static int binary_search_start(int *a, int size, int target)
{
int low = -1;
int high = size;
while (low + 1 < high) {
int mid = low + (high - low) / 2;
if (target > a[mid]) {
low = mid;
} else {
high = mid;
}
}

if (high == size || a[high] != target) {
return -1;
} else {
return high;
}
}

static int binary_search_end(int *a, int size, int target)
{
int low = -1;
int high = size;
while (low + 1 < high) {
int mid = low + (high - low) / 2;
if (target < a[mid]) {
high = mid;
} else {
low = mid;
}
}

if (low == -1 || a[low] != target) {
return -1;
} else {
return low;
}
}

/**
** Return an array of size *returnSize.
** Note: The returned array must be malloced, assume caller calls free().
**/
int* searchRange(int* nums, int numsSize, int target, int* returnSize) {
int *range = malloc(2 * sizeof(int));

if (numsSize == 0) {
range[0] = range[1] = -1;
return range;
}

range[0] = binary_search_start(nums, numsSize, target);
range[1] = binary_search_end(nums, numsSize, target);
*returnSize = 2;
return range;
}

int main(int argc, char **argv)
{
int i, count;
int *nums = malloc((argc - 2) * sizeof(int));
for (i = 0; i < argc - 2; i++) {
nums[i] = atoi(argv[i + 2]);
}

int *range = searchRange(nums, argc - 2, atoi(argv[1]), &count);
printf("%d %d\n", range[0], range[1]);

return 0;
}

0 comments on commit cee8800

Please sign in to comment.