查找数组中出现一次的元素,其他元素均出现两次
给定一个整数数组。除一个出现一次的数字外,所有数字都出现两次。在 O(n) 时间和恒定的额外空间中找到数字。
例子 :
输入:arr[] = {2, 3, 5, 4, 5, 3, 4}
输出:2
方法(暴力):双层遍历,检查每个元素是否出现一次。一旦找到单次出现的元素,就将其返回。
下面是该方法的实现:
C++
// C++ program to find the array element
// that appears only once
#include <iostream>
using namespace std;
// Function to find the
int findSingle(int A[], int ar_size)
{
// Iterate over every element
for (int i = 0; i < ar_size; i++) {
// Initialize count to 0
int count = 0;
for (int j = 0; j < ar_size; j++) {
// Count the frequency
// of the element
if (A[i] == A[j]) {
count++;
}
}
// if the frequency of the
// element is one
if (count == 1) {
return A[i];
}
}
// if no element exist at most once
return -1;
}
// Driver code
int main()
{
int ar[] = { 2, 3, 5, 4, 5, 3, 4 };
int n = sizeof(ar) / sizeof(ar[0]);
// Function call
cout << "Element occurring once is "
<< findSingle(ar, n);
return 0;
}
Java
/*package whatever //do not write package name here */
import java.io.*;
class GFG {
// Function to find the
static int findSingle(int A[], int ar_size)
{
// Iterate over every element
for (int i = 0; i < ar_size; i++) {
// Initialize count to 0
int count = 0;
for (int j = 0; j < ar_size; j++) {
// Count the frequency
// of the element
if (A[i] == A[j]) {
count++;
}
}
// if the frequency of the
// element is one
if (count == 1) {
return A[i];
}
}
// if no element exist at most once
return -1;
}
public static void main (String[] args) {
int ar[] = { 2, 3, 5, 4, 5, 3, 4 };
int n = ar.length;
// Function call
System.out.println("Element occurring once is " + findSingle(ar, n));
}
}
Python
# Python code to find the array element that appears only once
# Function to find the array
# element that appears only once
def findSingle(A, ar_size):
# iterate over every element
for i in range(ar_size):
# Initialize count to 0
count = 0
for j in range(ar_size):
# Count the frequency
# of the element
if(A[i] == A[j]):
count += 1
# If the frequency of
# the element is one
if(count == 1):
return A[i]
# If no element exist
# at most once
return -1
ar = [2, 3, 5, 4, 5, 3, 4]
n = len(ar)
# Function call
print("Element occurring once is", findSingle(ar, n))
C#
// Include namespace system
using System;
public class GFG
{
// Function to find the
public static int findSingle(int[] A, int ar_size)
{
// Iterate over every element
for (int i = 0; i < ar_size; i++)
{
// Initialize count to 0
var count = 0;
for (int j = 0; j < ar_size; j++)
{
// Count the frequency
// of the element
if (A[i] == A[j])
{
count++;
}
}
// if the frequency of the
// element is one
if (count == 1)
{
return A[i];
}
}
// if no element exist at most once
return -1;
}
public static void Main(String[] args)
{
int[] ar = {2, 3, 5, 4, 5, 3, 4};
var n = ar.Length;
// Function call
Console.WriteLine("Element occurring once is " +
GFG.findSingle(ar, n).ToString());
}
}
Javascript
// Javascript program to find the array element
// that appears only once
// Function to find the
function findSingle(A, ar_size)
{
// Iterate over every element
for (let i = 0; i < ar_size; i++) {
// Initialize count to 0
let count = 0;
for (let j = 0; j < ar_size; j++) {
// Count the frequency
// of the element
if (A[i] == A[j]) {
count++;
}
}
// if the frequency of the
// element is one
if (count == 1) {
return A[i];
}
}
// if no element exist at most once
return -1;
}
// Driver code
let ar = [ 2, 3, 5, 4, 5, 3, 4 ];
let n = 7;
// Function call
document.write("Element occurring once is "
+ findSingle(ar, n));
输出
Element occurring once is 2
该解决方案的时间复杂度为 O(n^2)
辅助空间:使用 O(1) 作为常数空间。
使用hash
- 遍历所有元素并将其放入哈希表中。元素用作键,出现次数用作哈希表中的值。
- 再次遍历数组,打印哈希表中计数为1的元素。
该解决方案的工作时间为 O(n),但需要额外的空间。
上述方法的代码:
C++
#include <bits/stdc++.h>
using namespace std;
int singleelement(int arr[], int n)
{
//hashmap to store frequency
unordered_map<int,int> mm;
for(int i=0;i<n;i++)
{
//storing frequency
mm[arr[i]]++;
}
//iterating over map
for(auto x:mm)
{
//returning element with frequency 1
if(x.second==1) return x.first;
}
}
int main()
{
int arr[] = { 2, 3, 5, 4, 5, 3, 4 };
int size = sizeof(arr) / sizeof(arr[0]);
sort(arr, arr + size);
cout << singleelement(arr, size);
return 0;
}
Python
def singleelement(arr, n):
#dictionary to store frequency
mm = {}
for i in range(n):
#storing frequency
if arr[i] in mm:
mm[arr[i]] += 1
else:
mm[arr[i]] = 1
#iterating over dictionary
for key, value in mm.items():
#returning element with frequency 1
if value == 1:
return key
#driver code
arr = [2, 3, 5, 4, 5, 3, 4]
size = len(arr)
arr.sort()
print(singleelement(arr, size))
C#
using System;
using System.Collections.Generic;
class Program {
static int SingleElement(int[] arr, int n)
{
// hashmap to store frequency
Dictionary<int, int> mm
= new Dictionary<int, int>();
for (int i = 0; i < n; i++)
{
// storing frequency
if (!mm.ContainsKey(arr[i])) {
mm[arr[i]] = 1;
}
else {
mm[arr[i]]++;
}
}
// iterating over map
foreach(KeyValuePair<int, int> x in mm)
{
// returning element with frequency 1
if (x.Value == 1)
return x.Key;
}
return 0;
}
static void Main(string[] args)
{
int[] arr = { 2, 3, 5, 4, 5, 3, 4 };
int size = arr.Length;
Array.Sort(arr);
Console.WriteLine(SingleElement(arr, size));
}
}
Java
import java.util.*;
public class GFG {
public static int singleElement(int[] arr)
{
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < arr.length; i++) {
int freq = map.getOrDefault(arr[i], 0);
map.put(arr[i], freq + 1);
}
for (int i = 0; i < arr.length; i++) {
if (map.get(arr[i]) == 1) {
return arr[i];
}
}
return -1; // indicates no unique element found
}
public static void main(String[] args)
{
int[] arr = { 2, 3, 5, 4, 5, 3, 4 };
Arrays.sort(arr);
int single = singleElement(arr);
if (single == -1) {
System.out.println("No unique element found");
}
else {
System.out.println("Unique element: " + single);
}
}
}
Javascript
function singleelement(arr, n)
{
//hashmap to store frequency
let mm = new Map();
for (let i=0;i<n;i++) {
if (mm.has(arr[i])) {
// If number is present in mm,
// incrementing it's count by 1
mm.set(arr[i], mm.get(arr[i]) + 1);
}
else {
// If integer is not present in mm,
// putting this integer to mm with 1 as it's value
mm.set(arr[i], 1);
}
}
//iterating over map
for (let [key, value] of mm.entries())
{
//returning element with frequency 1
if(value==1)
return key;
}
}
let arr = [2, 3, 5, 4, 5, 3, 4 ];
let size = arr.length;
arr.sort();
document.write(singleelement(arr, size));
输出
2
时间复杂度: O(N)
辅助空间: O(N)
最好的解决方案是使用 XOR。所有数组元素的异或给出了出现一次的数字。这个想法基于以下两个事实。
- 任何数和 0 做异或运算,结果仍然是原来的数,即 a⊕0=a
- 任何数和其自身做异或运算,结果是 0,即 a⊕a=0
- 异或运算满足交换律和结合律,即 a⊕b⊕a=b⊕a⊕a=b⊕(a⊕a)=b⊕0=b
res = 7 ^ 3 ^ 5 ^ 4 ^ 5 ^ 3 ^ 4
res = 7 ^ (3 ^ 3) ^ (4 ^ 4) ^ (5 ^ 5)
= 7 ^ 0 ^ 0 ^ 0
= 7 ^ 0
= 7
下面是上述算法的实现。
C++
// C++ program to find the array element
// that appears only once
#include <iostream>
using namespace std;
int findSingle(int ar[], int ar_size)
{
// Do XOR of all elements and return
int res = ar[0];
for (int i = 1; i < ar_size; i++)
res = res ^ ar[i];
return res;
}
// Driver code
int main()
{
int ar[] = { 2, 3, 5, 4, 5, 3, 4 };
int n = sizeof(ar) / sizeof(ar[0]);
cout << "Element occurring once is "
<< findSingle(ar, n);
return 0;
}
C
// C program to find the array element that appears only
// once
#include <stdio.h>
int findSingle(int ar[], int ar_size)
{
// Do XOR of all elements and return
int res = ar[0];
for (int i = 1; i < ar_size; i++)
res = res ^ ar[i];
return res;
}
// Driver code
int main()
{
int ar[] = { 2, 3, 5, 4, 5, 3, 4 };
int n = sizeof(ar) / sizeof(ar[0]);
printf("Element occurring once is %d",
findSingle(ar, n));
return 0;
}
Java
// Java program to find the array
// element that appears only once
import java.io.*;
class MaxSum
{
// Return the maximum Sum of difference
// between consecutive elements.
static int findSingle(int ar[], int ar_size)
{
// Do XOR of all elements and return
int res = ar[0];
for (int i = 1; i < ar_size; i++)
res = res ^ ar[i];
return res;
}
// Driver code
public static void main (String[] args)
{
int ar[] = {2, 3, 5, 4, 5, 3, 4};
int n = ar.length;
System.out.println("Element occurring once is " +
findSingle(ar, n) + " ");
}
}
Python
# function to find the once
# appearing element in array
def findSingle( ar, n):
res = ar[0]
# Do XOR of all elements and return
for i in range(1,n):
res = res ^ ar[i]
return res
# Driver code
ar = [2, 3, 5, 4, 5, 3, 4]
print "Element occurring once is", findSingle(ar, len(ar))
C#
// C# program to find the array
// element that appears only once
using System;
class GFG
{
// Return the maximum Sum of difference
// between consecutive elements.
static int findSingle(int []ar, int ar_size)
{
// Do XOR of all elements and return
int res = ar[0];
for (int i = 1; i < ar_size; i++)
res = res ^ ar[i];
return res;
}
// Driver code
public static void Main ()
{
int []ar = {2, 3, 5, 4, 5, 3, 4};
int n = ar.Length;
Console.Write("Element occurring once is " +
findSingle(ar, n) + " ");
}
}
PHP
<?php
// PHP program to find the array
// element that appears only once
function findSingle($ar, $ar_size)
{
// Do XOR of all
// elements and return
$res = $ar[0];
for ($i = 1; $i < $ar_size; $i++)
$res = $res ^ $ar[$i];
return $res;
}
// Driver code
$ar = array(2, 3, 5, 4, 5, 3, 4);
$n = count($ar);
echo "Element occurring once is "
, findSingle($ar, $n);
?>
Javascript
<script>
// JavaScript program to find the array
// element that appears only once
function findSingle(ar, ar_size)
{
// Do XOR of all elements and return
let res = ar[0];
for (let i = 1; i < ar_size; i++)
res = res ^ ar[i];
return res;
}
// Driver code
let ar = [2, 3, 5, 4, 5, 3, 4];
let n = ar.length;
document.write("Element occurring once is "
+ findSingle(ar, n));
</script>
输出
Element occurring once is 2
时间复杂度:O(n)
辅助空间:O(1)