diff options
author | jack <[email protected]> | 2024-06-14 13:13:15 -0600 |
---|---|---|
committer | jack <[email protected]> | 2024-06-14 13:13:15 -0600 |
commit | d343a3b18dbaca9297d4f7b2280c4a16f0a5c8aa (patch) | |
tree | 96df922dae2a5073d9a50ea70c7aae6aa37e3ebe /count_distinct_int.cpp | |
download | leetcode-d343a3b18dbaca9297d4f7b2280c4a16f0a5c8aa.tar.gz leetcode-d343a3b18dbaca9297d4f7b2280c4a16f0a5c8aa.zip |
initial
Diffstat (limited to 'count_distinct_int.cpp')
-rw-r--r-- | count_distinct_int.cpp | 40 |
1 files changed, 40 insertions, 0 deletions
diff --git a/count_distinct_int.cpp b/count_distinct_int.cpp new file mode 100644 index 0000000..ff5c1d6 --- /dev/null +++ b/count_distinct_int.cpp @@ -0,0 +1,40 @@ +// 2442. Count Number of Distinct Integers After Reverse Operations +#include "leetcode.h" + +/* + * array nums contains positive integers + * take each integer in array and reverse its digits (eg. 13 -> 31) + * then *add* it to end of array. return number of distinct integers. + * [1,13,10,12,31] becomes [1,13,10,12,31,1,31,1,21,13] + * and total num of distinct ints = 6 + */ + +class Solution { +public: + int countDistinctIntegers(vector<int> &nums) { + // unordered set constructor to insert 'nums' + // note: a set only maintains unique values in it + unordered_set<int> us(nums.begin(), nums.end()); + // find reverse of every num + for (auto i : nums) { + int n = 0; + while (i) { + int rem = i % 10; + n = n * 10 + rem; + i /= 10; + } + // insert (to end) reverse + us.insert(n); + } + // we can simply return the size since + // every element in a set is unique + return us.size(); + } +}; + +int main() { + Solution obj; + vector<int> nums1 = {1, 13, 10, 12, 31}, nums2 = {2, 2, 2}; + cout << obj.countDistinctIntegers(nums1) << endl; // expect: 6 + cout << obj.countDistinctIntegers(nums2) << endl; // expect: 1 +} |