diff options
author | jack <[email protected]> | 2024-06-14 13:13:15 -0600 |
---|---|---|
committer | jack <[email protected]> | 2024-06-14 13:13:15 -0600 |
commit | d343a3b18dbaca9297d4f7b2280c4a16f0a5c8aa (patch) | |
tree | 96df922dae2a5073d9a50ea70c7aae6aa37e3ebe /search_insert_pos.c | |
download | leetcode-d343a3b18dbaca9297d4f7b2280c4a16f0a5c8aa.tar.gz leetcode-d343a3b18dbaca9297d4f7b2280c4a16f0a5c8aa.zip |
initial
Diffstat (limited to 'search_insert_pos.c')
-rw-r--r-- | search_insert_pos.c | 28 |
1 files changed, 28 insertions, 0 deletions
diff --git a/search_insert_pos.c b/search_insert_pos.c new file mode 100644 index 0000000..cbbdcd9 --- /dev/null +++ b/search_insert_pos.c @@ -0,0 +1,28 @@ +// 35. Search Insert Position +#include <stdio.h> +#include <stdlib.h> + +/* + * given a sorted array of distinct intergers and a target value, return the + * index if the target is found. if not, return the index where it would be if + * it were inserted in order. must be o(ln) compexity + */ + +int searchInsert(int *nums, int numsSize, int target) { + int left = 0, right = numsSize, mid; + while (left < right) { + mid = left + (right - left) / 2; + if (nums[mid] >= target) + right = mid; + else + left = mid + 1; + } + return left; +} + +int main() { + int nums[] = {1, 3, 5, 6}, ns = 4; + printf("%d\n", searchInsert(nums, ns, 5)); // expect: 2 + printf("%d\n", searchInsert(nums, ns, 2)); // expect: 1 + printf("%d\n", searchInsert(nums, ns, 7)); // expect: 4 +} |