From 05cc4cd07c9a16d7712a5f4ce968eb27a6e83b92 Mon Sep 17 00:00:00 2001 From: Raghav1229 <115594501+Raghav1229@users.noreply.github.com> Date: Sun, 16 Oct 2022 08:02:37 +0530 Subject: [PATCH] Create Find the element that appears once in an array where every other element appears twice --- ...ay where every other element appears twice | 40 +++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 Find the element that appears once in an array where every other element appears twice diff --git a/Find the element that appears once in an array where every other element appears twice b/Find the element that appears once in an array where every other element appears twice new file mode 100644 index 0000000..83f9807 --- /dev/null +++ b/Find the element that appears once in an array where every other element appears twice @@ -0,0 +1,40 @@ +// C++ program to find +// element that appears once +#include + +using namespace std; + +// function which find number +int singleNumber(int nums[],int n) +{ + map m; + long sum1 = 0,sum2 = 0; + + for(int i = 0; i < n; i++) + { + if(m[nums[i]] == 0) + { + sum1 += nums[i]; + m[nums[i]]++; + } + sum2 += nums[i]; + } + + // applying the formula. + return 2 * (sum1) - sum2; +} + +// Driver code +int main() +{ + int a[] = {2, 3, 5, 4, 5, 3, 4}; + int n = 7; + cout << singleNumber(a,n) << "\n"; + + int b[] = {15, 18, 16, 18, 16, 15, 89}; + + cout << singleNumber(b,n); + return 0; +} + +// This code is contributed by mohit kumar 29