Advertisement
LordMZTE

Untitled

Jun 4th, 2023
814
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.97 KB | None | 0 0
  1. #include <stddef.h>
  2.  
  3. #define COUNTS_LEN 128
  4.  
  5. int find_odd (size_t length, const int array[length]) {
  6.   // counts of positive numbers
  7.   int pos_counts[COUNTS_LEN];
  8.   // counts of negative numbers; indices are absolute values
  9.   int neg_counts[COUNTS_LEN];
  10.  
  11.   // initialize counts arrays to -1
  12.   for (int i = 0; i < COUNTS_LEN; i++)
  13.     neg_counts[i] = pos_counts[i] = -1;
  14.  
  15.   // count up numbers
  16.   for (int i = 0; i < length; i++) {
  17.     int n = array[i];
  18.    
  19.     if (n < 0) {
  20.       if (neg_counts[-n] < 0)
  21.         neg_counts[-n] = 0;
  22.       neg_counts[-n] += 1;
  23.     } else {
  24.       if (pos_counts[n] < 0)
  25.         pos_counts[n] = 0;
  26.       pos_counts[n] += 1;
  27.     }
  28.   }
  29.  
  30.   // check pos counts
  31.   for (int i = 0; i < COUNTS_LEN; i++)
  32.     if (pos_counts[i] >= 0 && pos_counts[i] % 2 != 0)
  33.       return i;
  34.  
  35.   // check neg counts
  36.   for (int i = 0; i < COUNTS_LEN; i++)
  37.     if (neg_counts[i] >= 0 && neg_counts[i] % 2 != 0)
  38.       return -i;
  39.  
  40.   return 0;
  41. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement