Problem 1: two sum

This commit is contained in:
Ivan R. 2022-11-17 15:45:40 +05:00
parent a7fc06a74b
commit 16ef234336
No known key found for this signature in database
GPG key ID: 56C7BAAE859B302C
6 changed files with 80 additions and 0 deletions

2
.gitignore vendored Normal file
View file

@ -0,0 +1,2 @@
*.o
bin

View file

@ -0,0 +1,14 @@
all: lib.o main.o
gcc -Wall -o bin lib.o main.o
lib.o: lib.c
gcc -c -Wall lib.c
main.o: main.c
gcc -c -Wall main.c
run:
./bin
clean:
rm *.o bin

18
problems/1-two-sum/lib.c Normal file
View file

@ -0,0 +1,18 @@
#include <stdlib.h>
#include "lib.h"
int* twoSum(int* nums, int numsSize, int target, int* returnSize) {
for (int i=0; i<numsSize-1; i++) {
for (int j=i+1; j<numsSize; j++) {
if (nums[i] + nums[j] == target) {
int* res = malloc(2 * sizeof(int));
res[0] = i;
res[1] = j;
*returnSize = 2;
return res;
}
}
}
*returnSize = 0;
return NULL;
}

2
problems/1-two-sum/lib.h Normal file
View file

@ -0,0 +1,2 @@
#pragma once
int* twoSum(int* nums, int numsSize, int target, int* returnSize);

35
problems/1-two-sum/main.c Normal file
View file

@ -0,0 +1,35 @@
#include "stdio.h"
#include "stdlib.h"
#include "lib.h"
int main() {
int returnSize = -1;
int nums1[] = {2, 7, 11, 15};
int target1 = 9;
int* res1 = twoSum(nums1, 4, target1, &returnSize);
if (returnSize == 2 && res1[0] == 0 && res1[1] == 1) {
printf("Test 1: passed\n");
}
else {
printf("Test 1: failed\n");
}
if (returnSize > 0) {
free(res1);
}
int nums2[] = {3, 2, 4};
int target2 = 6;
int* res2 = twoSum(nums2, 3, target2, &returnSize);
if (returnSize == 2 && res2[0] == 1 && res2[1] == 2) {
printf("Test 2: passed\n");
}
else {
printf("Test 2: failed\n");
}
if (returnSize > 0) {
free(res2);
}
return 0;
}

View file

@ -0,0 +1,9 @@
# 1. Two sum
Given an array of integers nums and an integer target,
return indices of the two numbers such that they add up to target.
You may assume that each input would have exactly one solution,
and you may not use the same element twice.
You can return the answer in any order.