Online store~15 min2s · 256 MBtarget O(n) time, O(n) spaceclassic twin: lc-1748hashing
A shop gives every coupon a code number. Customers redeem coupons during a sale, and the list of redeemed codes can hold the same code many times.
Finance wants a control total over the codes that were redeemed exactly once. A code that was redeemed twice or more is not counted at all, not even once.
The list can hold 100,000 redeemed codes, and each code is a number up to 10,000,000.
Write sum_of_unique(values).
values[i] is the code of one redeemed coupon.values.Input: values = [3, 1, 3, 2, 4, 2, 5]
Output: 10Counting the copies of each code gives this table.
| Code | Copies | Unique |
|---|---|---|
| 1 | 1 | yes |
| 2 | 2 | no |
| 3 | 2 | no |
| 4 | 1 | yes |
| 5 | 1 | yes |
The unique codes are 1, 4 and 5, and their sum is 10.
Input: values = [7, 7, 7]
Output: 0A code that appears three times is not unique.
Input: values = [9]
Output: 9A single code appears once.
1 ≤ values.length ≤ 100,000 (redeemed coupons)1 ≤ values[i] ≤ 10,000,000 (coupon code)Counting the copies of each entry by scanning the list costs about 10^10 comparisons for 100,000 entries.
One pass builds a table of counts, and one pass over the table adds the codes with count 1. The total can reach 9,999,500,500 for 1,000 large codes, and 100,000 of them pass 2 × 10^9, so use 64-bit integers.