📌  相关文章
📜  数组中唯一的元素,其中所有元素都出现K次,一次|套装2

📅  最后修改于: 2021-05-14 01:10:22             🧑  作者: Mango

给定一个数组arr [] ,其中每个元素出现K次,但一个元素仅出现一次,任务是找到该唯一元素。
例子:

天真的方法:假设每个元素有K次,则给定数组中所有元素的总和与所有唯一元素K * sum之差是唯一元素(K-1)倍
例如:

步骤如下:

  1. 将给定数组的所有元素存储在集合中以获得唯一元素。
  2. 查找数组中所有元素的总和(例如sum_array )和集合中所有元素的总和(例如sum_set )。
  3. 唯一元素由(K * sum_set – sum_array)/(K – 1)给出

下面是上述方法的实现:

C++
// C++ program for the above approach
 
#include 
using namespace std;
 
// Function that find the unique element
// in the array arr[]
int findUniqueElements(int arr[], int N,
                       int K)
{
    // Store all unique element in set
    unordered_set s(arr, arr + N);
 
    // Sum of all element of the array
    int arr_sum = accumulate(arr, arr + N, 0);
 
    // Sum of element in the set
    int set_sum = accumulate(s.begin(),
                             s.end(),
                             0);
 
    // Print the unique element using formula
    cout << (K * set_sum - arr_sum) / (K - 1);
}
 
// Driver Code
int main()
{
 
    int arr[] = { 12, 1, 12, 3, 12, 1,
                  1, 2, 3, 2, 2, 3, 7 };
    int N = sizeof(arr) / sizeof(arr[0]);
    int K = 3;
 
    // Function call
    findUniqueElements(arr, N, K);
 
    return 0;
}


Java
// Java program for the above approach
import java.util.*;
 
class GFG{
     
// Function that find the unique element
// in the array arr[]
static void findUniqueElements(int arr[],
                               int N, int K)
{
     
    // Store all unique element in set
    Set s = new HashSet<>();
    for(int i = 0; i < N; i++)
        s.add(arr[i]);
 
    // Sum of all element of the array
    int arr_sum = 0;
    for(int i = 0; i < N; i++)
        arr_sum += arr[i];
 
    // Sum of element in the set
    int set_sum = 0;
    Iterator it = s.iterator();
 
    while (it.hasNext())
    {
        set_sum += (int)it.next();
    }
 
    // Print the unique element using formula
    System.out.println((K * set_sum - arr_sum) /
                       (K - 1));
}
 
// Driver code
public static void main(String[] args)
{
    int arr[] = { 12, 1, 12, 3, 12, 1,
                  1, 2, 3, 2, 2, 3, 7 };
    int N = arr.length;
    int K = 3;
 
    // Function call
    findUniqueElements(arr, N, K);
}
}
 
// This code is contributed by offbeat


Python3
# Python3 program for the above approach
 
# Function that find the unique element
# in the array arr[]
def findUniqueElements(arr, N, K):
     
    # Store all unique element in set
    s = set()
    for x in arr:
        s.add(x)
 
    # Sum of all element of the array
    arr_sum = sum(arr)
 
    # Sum of element in the set
    set_sum = 0
    for x in s:
        set_sum += x
 
    # Print the unique element using formula
    print((K * set_sum - arr_sum) // (K - 1))
 
# Driver Code
if __name__ == '__main__':
     
    arr = [ 12, 1, 12, 3, 12, 1,
            1, 2, 3, 2, 2, 3, 7 ]
    N = len(arr)
    K = 3
 
    # Function call
    findUniqueElements(arr, N, K)
 
# This code is contributed by Samarth


C#
// C# program for the above approach
using System;
using System.Collections.Generic;
class GFG{
     
// Function that find the unique element
// in the array []arr
static void findUniqueElements(int []arr,
                               int N, int K)
{
     
    // Store all unique element in set
    HashSet s = new HashSet();
    for(int i = 0; i < N; i++)
        s.Add(arr[i]);
 
    // Sum of all element of the array
    int arr_sum = 0;
    for(int i = 0; i < N; i++)
        arr_sum += arr[i];
 
    // Sum of element in the set
    int set_sum = 0;
    foreach(int i in s)
        set_sum += i;
 
 
    // Print the unique element using formula
    Console.WriteLine((K * set_sum - arr_sum) /
                      (K - 1));
}
 
// Driver code
public static void Main(String[] args)
{
    int []arr = { 12, 1, 12, 3, 12, 1,
                  1, 2, 3, 2, 2, 3, 7 };
    int N = arr.Length;
    int K = 3;
 
    // Function call
    findUniqueElements(arr, N, K);
}
}
 
// This code is contributed by gauravrajput1


C++
// CPP program for the above approach
#include 
using namespace std;
 
// Function to find single occurance element
int findunique(vector& a, int k)
{
    int res = 0;
 
    for (int i = 0; i < 32; i++) {
        int p = 0;
 
        for (int j = 0; j < a.size(); j++) {
            // By shifting 1 to left ith
            // time and taking and with 1
            // will give us that ith
            // bit of a[j] is 1 or 0
            p += (abs(a[j]) & (
                  1 << i)) != 0 ? 1 : 0;
        }
 
        // Taking modulo of p with k
        p %= k;
 
        // Generate result
        res += pow(2, i) * p;
    }
 
    int c = 0;
 
    // Loop for negative numbers
    for (auto x : a)
 
        if (x == res) {
            c = 1;
            break;
        }
   
    // Check if the calculated value res
    // is present in array, then mark c=1
    // and if c = 1 return res
    // else res must be -ve
    return c == 1 ? res : -res;
}
 
// Driver code
int main()
{
 
    vector a = { 12, 12, 2, 2, 3 };
    int k = 2;
 
    // Function call
    cout << findunique(a, k) << "\n";
}
// This article is contributed by ajaykr00kj


Java
// Java program for the above approach
import java.util.Arrays;
class Main{
     
// Function to find single
// occurance element
public static int findunique(int a[],
                             int k)
{
  int res = 0;
 
  for (int i = 0; i < 32; i++)
  {
    int p = 0;
 
    for (int j = 0; j < a.length; j++)
    {
      // By shifting 1 to left ith
      // time and taking and with 1
      // will give us that ith
      // bit of a[j] is 1 or 0
      p += (Math.abs(a[j]) &
           (1 << i)) != 0 ? 1 : 0;
    }
 
    // Taking modulo of p with k
    p %= k;
 
    // Generate result
    res += Math.pow(2, i) * p;
  }
 
  int c = 0;
 
  // Loop for negative numbers
  for (int x = 0; x < a.length; x++)
 
    if (a[x] == res)
    {
      c = 1;
      break;
    }
 
  // Check if the calculated value res
  // is present in array, then mark c=1
  // and if c = 1 return res
  // else res must be -ve
  return c == 1 ? res : -res;
}
 
// Driver code
public static void main(String[] args)
{
  int a[] = {12, 12, 2, 2, 3};
  int k = 2;
 
  // Function call
  System.out.println(findunique(a, k));
}
}
 
// This code is contributed by divyeshrabadiya07


Python3
# Python3 program for the above approach
 
# Function to find single occurance element
def findunique(a, k):
 
    res = 0
 
    for i in range(32):
        p = 0
 
        for j in range(len(a)):
           
            # By shifting 1 to left ith
            # time and taking and with 1
            # will give us that ith
            # bit of a[j] is 1 or 0
            if (abs(a[j]) & (1 << i)) != 0 :
                p += 1
 
        # Taking modulo of p with k
        p %= k
 
        # Generate result
        res += pow(2, i) * p
 
    c = 0
 
    # Loop for negative numbers
    for x in a:
 
        if (x == res) :
            c = 1
            break
 
    # Check if the calculated value res
    # is present in array, then mark c=1
    # and if c = 1 return res
    # else res must be -ve
    if c == 1 :
        return res
    else :
        return -res
 
# Driver code
a = [ 12, 12, 2, 2, 3 ]
k = 2
 
# Function call
print(findunique(a, k))
 
# This code is contributed by divyesh072019


C#
// C# program for the
// above approach
using System;
class GFG{
      
// Function to find single
// occurance element
public static int findunique(int []a,
                             int k)
{
  int res = 0;
  
  for (int i = 0; i < 32; i++)
  {
    int p = 0;
  
    for (int j = 0; j < a.Length; j++)
    {
      // By shifting 1 to left ith
      // time and taking and with 1
      // will give us that ith
      // bit of a[j] is 1 or 0
      p += (Math.Abs(a[j]) &
           (1 << i)) != 0 ? 1 : 0;
    }
  
    // Taking modulo of p with k
    p %= k;
  
    // Generate result
    res += (int)Math.Pow(2, i) * p;
  }
  
  int c = 0;
  
  // Loop for negative numbers
  for (int x = 0; x < a.Length; x++)
  
    if (a[x] == res)
    {
      c = 1;
      break;
    }
  
  // Check if the calculated value res
  // is present in array, then mark c=1
  // and if c = 1 return res
  // else res must be -ve
  return c == 1 ? res : -res;
}
  
// Driver code
public static void Main(string []args)
{
  int []a = {12, 12, 2, 2, 3};
  int k = 2;
  
  // Function call
  Console.Write(findunique(a, k));
}
}
 
// This code is contributed by Rutvik_56


Javascript


输出
7

时间复杂度: O(N) ,其中N是数组中元素的数量
辅助空间复杂度: O(N / K) ,其中K为频率。

另一种方法:想法是使用散列,但是这将花费O(n)时间,并且需要额外的空间。我们也可以通过排序来完成,但这将花费O(N log N)的时间。

高效方法:可以根据恒定的空间复杂度来优化上述问题。使用位操作方法可以解决此问题。

  • 假设有一种情况,所有元素除1个元素外均出现k次。
  • 因此,计算每个元素的位为32位。
  • 计算每个元素的第0位并以k为模,将消除出现k次的元素位,而我们只剩下出现一次的元素位。
  • 对所有32位应用此过程,并通过对k取模,我们将消除重复元素的位。
  • 在每一步中,从这些剩余的位生成结果。
  • 要处理任何负数,请检查结果是否存在于数组中,如果存在,则将其打印出来。否则打印结果为负。

下面是上述方法的实现:

C++

// CPP program for the above approach
#include 
using namespace std;
 
// Function to find single occurance element
int findunique(vector& a, int k)
{
    int res = 0;
 
    for (int i = 0; i < 32; i++) {
        int p = 0;
 
        for (int j = 0; j < a.size(); j++) {
            // By shifting 1 to left ith
            // time and taking and with 1
            // will give us that ith
            // bit of a[j] is 1 or 0
            p += (abs(a[j]) & (
                  1 << i)) != 0 ? 1 : 0;
        }
 
        // Taking modulo of p with k
        p %= k;
 
        // Generate result
        res += pow(2, i) * p;
    }
 
    int c = 0;
 
    // Loop for negative numbers
    for (auto x : a)
 
        if (x == res) {
            c = 1;
            break;
        }
   
    // Check if the calculated value res
    // is present in array, then mark c=1
    // and if c = 1 return res
    // else res must be -ve
    return c == 1 ? res : -res;
}
 
// Driver code
int main()
{
 
    vector a = { 12, 12, 2, 2, 3 };
    int k = 2;
 
    // Function call
    cout << findunique(a, k) << "\n";
}
// This article is contributed by ajaykr00kj

Java

// Java program for the above approach
import java.util.Arrays;
class Main{
     
// Function to find single
// occurance element
public static int findunique(int a[],
                             int k)
{
  int res = 0;
 
  for (int i = 0; i < 32; i++)
  {
    int p = 0;
 
    for (int j = 0; j < a.length; j++)
    {
      // By shifting 1 to left ith
      // time and taking and with 1
      // will give us that ith
      // bit of a[j] is 1 or 0
      p += (Math.abs(a[j]) &
           (1 << i)) != 0 ? 1 : 0;
    }
 
    // Taking modulo of p with k
    p %= k;
 
    // Generate result
    res += Math.pow(2, i) * p;
  }
 
  int c = 0;
 
  // Loop for negative numbers
  for (int x = 0; x < a.length; x++)
 
    if (a[x] == res)
    {
      c = 1;
      break;
    }
 
  // Check if the calculated value res
  // is present in array, then mark c=1
  // and if c = 1 return res
  // else res must be -ve
  return c == 1 ? res : -res;
}
 
// Driver code
public static void main(String[] args)
{
  int a[] = {12, 12, 2, 2, 3};
  int k = 2;
 
  // Function call
  System.out.println(findunique(a, k));
}
}
 
// This code is contributed by divyeshrabadiya07

Python3

# Python3 program for the above approach
 
# Function to find single occurance element
def findunique(a, k):
 
    res = 0
 
    for i in range(32):
        p = 0
 
        for j in range(len(a)):
           
            # By shifting 1 to left ith
            # time and taking and with 1
            # will give us that ith
            # bit of a[j] is 1 or 0
            if (abs(a[j]) & (1 << i)) != 0 :
                p += 1
 
        # Taking modulo of p with k
        p %= k
 
        # Generate result
        res += pow(2, i) * p
 
    c = 0
 
    # Loop for negative numbers
    for x in a:
 
        if (x == res) :
            c = 1
            break
 
    # Check if the calculated value res
    # is present in array, then mark c=1
    # and if c = 1 return res
    # else res must be -ve
    if c == 1 :
        return res
    else :
        return -res
 
# Driver code
a = [ 12, 12, 2, 2, 3 ]
k = 2
 
# Function call
print(findunique(a, k))
 
# This code is contributed by divyesh072019

C#

// C# program for the
// above approach
using System;
class GFG{
      
// Function to find single
// occurance element
public static int findunique(int []a,
                             int k)
{
  int res = 0;
  
  for (int i = 0; i < 32; i++)
  {
    int p = 0;
  
    for (int j = 0; j < a.Length; j++)
    {
      // By shifting 1 to left ith
      // time and taking and with 1
      // will give us that ith
      // bit of a[j] is 1 or 0
      p += (Math.Abs(a[j]) &
           (1 << i)) != 0 ? 1 : 0;
    }
  
    // Taking modulo of p with k
    p %= k;
  
    // Generate result
    res += (int)Math.Pow(2, i) * p;
  }
  
  int c = 0;
  
  // Loop for negative numbers
  for (int x = 0; x < a.Length; x++)
  
    if (a[x] == res)
    {
      c = 1;
      break;
    }
  
  // Check if the calculated value res
  // is present in array, then mark c=1
  // and if c = 1 return res
  // else res must be -ve
  return c == 1 ? res : -res;
}
  
// Driver code
public static void Main(string []args)
{
  int []a = {12, 12, 2, 2, 3};
  int k = 2;
  
  // Function call
  Console.Write(findunique(a, k));
}
}
 
// This code is contributed by Rutvik_56

Java脚本


输出
3

时间复杂度: O(32 * n)= O(n)
辅助空间: O(1)