|
| 1 | +#include <stdio.h> |
| 2 | +#include <stdlib.h> |
| 3 | + |
| 4 | +// Function to find two indices such that their values add up to the target |
| 5 | +// Returns dynamic array of indices or NULL if no solution is found |
| 6 | +int* twoSum(int* nums, int numsSize, int target, int* returnSize) { |
| 7 | + // Allocate memory for the return array |
| 8 | + int* indices = (int*)malloc(2 * sizeof(int)); |
| 9 | + *returnSize = 0; // Initialize returnSize to 0 |
| 10 | + |
| 11 | + // Check all pairs of numbers |
| 12 | + for (int i = 0; i < numsSize; i++) { |
| 13 | + for (int j = i + 1; j < numsSize; j++) { |
| 14 | + // Check if the sum of the two numbers equals the target |
| 15 | + if (nums[i] + nums[j] == target) { |
| 16 | + indices[0] = i; // First index |
| 17 | + indices[1] = j; // Second index |
| 18 | + *returnSize = 2; // Set returnSize to 2 |
| 19 | + return indices; // Return the indices |
| 20 | + } |
| 21 | + } |
| 22 | + } |
| 23 | + |
| 24 | + // Return NULL if no indices found |
| 25 | + free(indices); |
| 26 | + return NULL; |
| 27 | +} |
| 28 | + |
| 29 | +// Example usage of the twoSum function |
| 30 | +int main() { |
| 31 | + int nums[] = {2, 7, 11, 15}; // Example array |
| 32 | + int target = 9; // Example target sum |
| 33 | + int returnSize = 0; // Size of the return array |
| 34 | + |
| 35 | + // Call the twoSum function |
| 36 | + int* result = twoSum(nums, sizeof(nums) / sizeof(nums[0]), target, &returnSize); |
| 37 | + |
| 38 | + // Check if result is found |
| 39 | + if (result != NULL) { |
| 40 | + printf("Indices: %d, %d\n", result[0], result[1]); // Output the indices |
| 41 | + free(result); // Free allocated memory |
| 42 | + } else { |
| 43 | + printf("No two sum solution found.\n"); // Output if no solution |
| 44 | + } |
| 45 | + |
| 46 | + return 0; // Exit the program |
| 47 | +} |
0 commit comments