fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. int* findDuplicates(int* nums, int numsSize, int* returnSize) {
  5. *returnSize = 0; // Initialize the size of the result array
  6. int* result = (int*)malloc(numsSize * sizeof(int)); // Allocate space for the result array
  7.  
  8. for (int i = 0; i < numsSize; i++) {
  9. int index = abs(nums[i]) - 1; // Get the index based on the value in the array
  10.  
  11. // If the number at that index is negative, the number has been seen before
  12. if (nums[index] < 0) {
  13. result[(*returnSize)++] = abs(nums[i]); // Add the duplicate to the result array
  14. } else {
  15. nums[index] = -nums[index]; // Mark the number as seen by negating it
  16. }
  17. }
  18.  
  19. return result;
  20. }
  21.  
  22. int main() {
  23. int nums[] = {4, 3, 2, 7, 8, 2, 3, 1}; // Example input
  24. int numsSize = sizeof(nums) / sizeof(nums[0]);
  25. int returnSize;
  26.  
  27. int* result = findDuplicates(nums, numsSize, &returnSize); // Find duplicates
  28.  
  29. printf("Duplicates: ");
  30. for (int i = 0; i < returnSize; i++) {
  31. printf("%d ", result[i]); // Print the result
  32. }
  33.  
  34. free(result); // Free the allocated memory for the result array
  35. return 0;
  36. }
  37.  
Success #stdin #stdout 0s 5276KB
stdin
Standard input is empty
stdout
Duplicates: 2 3