📜  查找排序数组中出现一次的元素

📅  最后修改于: 2021-09-16 10:53:06             🧑  作者: Mango

给定一个排序数组,其中所有元素出现两次(一个接一个),一个元素只出现一次。在 O(log n) 复杂度中找到该元素。

例子:

Input:   arr[] = {1, 1, 3, 3, 4, 5, 5, 7, 7, 8, 8}
Output:  4

Input:   arr[] = {1, 1, 3, 3, 4, 4, 5, 5, 7, 7, 8}
Output:  8

一个简单的解决方案是从左到右遍历数组。由于数组已排序,我们可以很容易地找出所需的元素。

下面是上述方法的实现。

C++
// C++ program to find the element that
// appears only once
#include 
using namespace std;
 
// A Linear Search based function to find
// the element that appears only once
void search(int arr[], int n)
{
    int ans = -1;
    for (int i = 0; i < n; i += 2) {
        if (arr[i] != arr[i + 1]) {
            ans = arr[i];
            break;
        }
    }
   
    if (arr[n - 2] != arr[n - 1])
            ans = arr[n-1];
   
    // ans = -1 if no such element is present.
    cout << "The required element is " << ans << "\n";
}
 
// Driver code
int main()
{
    int arr[] = { 1, 1, 2, 4, 4, 5, 5, 6, 6 };
    int len = sizeof(arr) / sizeof(arr[0]);
 
    search(arr, len);
 
    return 0;
}
 
// This code is contributed by yashbeersingh42


Java
// Java program to find the element that
// appears only once
import java.io.*;
 
class GFG {
    // A Linear Search based function to find
    // the element that appears only once
    static void search(int arr[], int n)
    {
        int ans = -1;
        for (int i = 0; i < n; i += 2) {
            if (arr[i] != arr[i + 1]) {
                ans = arr[i];
                break;
            }
        }
       
        if (arr[n - 2] != arr[n - 1])
            ans = arr[n-1];
      
        // ans = -1 if no such element is present.
        System.out.println("The required element is "
                           + ans);
    }
    public static void main(String[] args)
    {
        int arr[] = { 1, 1, 2, 4, 4, 5, 5, 6, 6 };
        int len = arr.length;
 
        search(arr, len);
    }
}


Python3
# Python3 program to find the element that
# appears only once
 
# A Linear Search based function to find
# the element that appears only once
 
 
def search(arr, n):
 
    ans = -1
    for i in range(0, n, 2):
        if (arr[i] != arr[i + 1]):
            ans = arr[i]
            break
    if(arr[n-2] != arr[n-1]):
        ans = arr[n-1]
 
    # ans = -1 if no such element is present.
    print("The required element is", ans)
 
 
# Driver code
arr = [1, 1, 2, 4, 4, 5, 5, 6, 6]
Len = len(arr)
 
search(arr, Len)
 
# This code is contributed by divyesh072019


C#
// C# program to find the element that
// appears only once
using System;
 
class GFG {
    // A Linear Search based function to find
    // the element that appears only once
    static void search(int[] arr, int n)
    {
        int ans = -1;
        for (int i = 0; i < n; i += 2) {
            if (arr[i] != arr[i + 1]) {
                ans = arr[i];
                break;
            }
        }
 
        if (arr[n - 2] != arr[n - 1])
            ans = arr[n-1];
       
        // ans = -1 if no such element is present.
        Console.Write("The required element is "
                        + ans);
    }
    public static void Main(String[] args)
    {
        int[] arr = { 1, 1, 2, 4, 4, 5, 5, 6, 6 };
        int len = arr.Length;
 
        search(arr, len);
    }
}
 
// This code is contributed by shivanisinghss2110


Javascript


C++
// C++ program to find the element that
// appears only once
#include 
using namespace std;
 
// A XOR based function to find
// the element that appears only once
void search(int arr[], int n)
{
    int XOR = 0;
    for (int i = 0; i < n; i++) {
        XOR = XOR ^ arr[i];
    }
    cout << "The required element is " << XOR << "\n";
}
 
// Driver code
int main()
{
    int arr[] = { 1, 1, 2, 4, 4, 5, 5, 6, 6 };
    int len = sizeof(arr) / sizeof(arr[0]);
 
    search(arr, len);
 
    return 0;
}
 
// This code is contributed by yashbeersingh42


Java
// Java program to find the element that
// appears only once
import java.io.*;
 
class GFG {
    // A XOR based function to find
    // the element that appears only once
    static void search(int arr[], int n)
    {
        int XOR = 0;
        for (int i = 0; i < n; i++) {
            XOR = XOR ^ arr[i];
        }
        System.out.println("The required element is "
                           + XOR);
    }
    // Driver Code
    public static void main(String[] args)
    {
        int arr[] = { 1, 1, 2, 4, 4, 5, 5, 6, 6 };
        int len = arr.length;
 
        search(arr, len);
    }
}
 
// This code is contributed by yashbeersingh42


Python3
# Python3 program to find the element that
# appears only once
 
# A XOR based function to find
# the element that appears only once
def search(arr, n) :
 
    XOR = 0
    for i in range(n) :
        XOR = XOR ^ arr[i]
 
    print("The required element is", XOR)
 
# Driver code
arr = [ 1, 1, 2, 4, 4, 5, 5, 6, 6 ]
Len = len(arr)
 
search(arr, Len)
 
# This code is contributed by divyesh072019


C#
// C# program to find the element that
// appears only once
using System;
 
class GFG{
     
// A XOR based function to find
// the element that appears only once
static void search(int []arr, int n)
{
    int XOR = 0;
     
    for(int i = 0; i < n; i++)
    {
        XOR = XOR ^ arr[i];
    }
    Console.Write("The required element is " + XOR);
}
 
// Driver Code
public static void Main(String[] args)
{
    int []arr = { 1, 1, 2, 4, 4, 5, 5, 6, 6 };
    int len = arr.Length;
     
    search(arr, len);
}
}
 
// This code is contributed by shivanisinghss2110


Javascript


C++
// C++ program to find the element that
// appears only once
#include 
using namespace std;
 
// A Binary Search based function to find
// the element that appears only once
void search(int arr[], int low, int high)
{
 
    // Base cases
    if (low > high)
        return;
 
    if (low == high) {
        cout << "The required element is " << arr[low];
        return;
    }
 
    // Find the middle point
    int mid = (low + high) / 2;
 
    // If mid is even and element next to mid is
    // same as mid, then output element lies on
    // right side, else on left side
    if (mid % 2 == 0) {
        if (arr[mid] == arr[mid + 1])
            search(arr, mid + 2, high);
        else
            search(arr, low, mid);
    }
 
    // If mid is odd
    else {
        if (arr[mid] == arr[mid - 1])
            search(arr, mid + 1, high);
        else
            search(arr, low, mid - 1);
    }
}
 
// Driver code
int main()
{
    int arr[] = { 1, 1, 2, 4, 4, 5, 5, 6, 6 };
    int len = sizeof(arr) / sizeof(arr[0]);
 
    search(arr, 0, len - 1);
 
    return 0;
}
 
// This code is contributed by ShubhamCoder


C
// C program to find the element that appears only once
#include 
 
// A Binary Search based function to find the element
// that appears only once
void search(int* arr, int low, int high)
{
    // Base cases
    if (low > high)
        return;
 
    if (low == high) {
        printf("The required element is %d ", arr[low]);
        return;
    }
 
    // Find the middle point
    int mid = (low + high) / 2;
 
    // If mid is even and element next to mid is
    // same as mid, then output element lies on
    // right side, else on left side
    if (mid % 2 == 0) {
        if (arr[mid] == arr[mid + 1])
            search(arr, mid + 2, high);
        else
            search(arr, low, mid);
    }
    else // If mid is odd
    {
        if (arr[mid] == arr[mid - 1])
            search(arr, mid + 1, high);
        else
            search(arr, low, mid - 1);
    }
}
 
// Driver code
int main()
{
    int arr[] = { 1, 1, 2, 4, 4, 5, 5, 6, 6 };
    int len = sizeof(arr) / sizeof(arr[0]);
    search(arr, 0, len - 1);
    return 0;
}


Java
// Java program to find the element that appears only once
 
public class Main {
    // A Binary Search based method to find the element
    // that appears only once
    public static void search(int[] arr, int low, int high)
    {
        if (low > high)
            return;
        if (low == high) {
            System.out.println("The required element is "
                               + arr[low]);
            return;
        }
 
        // Find the middle point
        int mid = (low + high) / 2;
 
        // If mid is even and element next to mid is
        // same as mid, then output element lies on
        // right side, else on left side
        if (mid % 2 == 0) {
            if (arr[mid] == arr[mid + 1])
                search(arr, mid + 2, high);
            else
                search(arr, low, mid);
        }
        // If mid is odd
        else if (mid % 2 == 1) {
            if (arr[mid] == arr[mid - 1])
                search(arr, mid + 1, high);
            else
                search(arr, low, mid - 1);
        }
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        int[] arr = { 1, 1, 2, 4, 4, 5, 5, 6, 6 };
        search(arr, 0, arr.length - 1);
    }
}
// This code is contributed by Tanisha Mittal


Python
# A Binary search based function to find
# the element that appears only once
 
 
def search(arr, low, high):
 
    # Base cases
    if low > high:
        return None
 
    if low == high:
        return arr[low]
 
    # Find the middle point
    mid = low + (high - low)/2
 
    # If mid is even and element next to mid is
    # same as mid, then output element lies on
    # right side, else on left side
    if mid % 2 == 0:
 
        if arr[mid] == arr[mid+1]:
            return search(arr, mid+2, high)
        else:
            return search(arr, low, mid)
 
    else:
        # if mid is odd
        if arr[mid] == arr[mid-1]:
            return search(arr, mid+1, high)
        else:
            return search(arr, low, mid-1)
 
# Driver Code
# Test Array
arr = [1, 1, 2, 4, 4, 5, 5, 6, 6]
 
# Function call
result = search(arr, 0, len(arr)-1)
 
if result is not None:
    print "The required element is %d" % result
else:
    print "Invalid Array"


C#
// C# program to find the element
// that appears only once
using System;
 
class GFG {
 
    // A Binary Search based
    // method to find the element
    // that appears only once
    public static void search(int[] arr, int low, int high)
    {
 
        if (low > high)
            return;
        if (low == high) {
            Console.WriteLine("The required element is "
                              + arr[low]);
            return;
        }
 
        // Find the middle point
        int mid = (low + high) / 2;
 
        // If mid is even and element
        // next to mid is same as mid
        // then output element lies on
        // right side, else on left side
        if (mid % 2 == 0) {
            if (arr[mid] == arr[mid + 1])
                search(arr, mid + 2, high);
            else
                search(arr, low, mid);
        }
 
        // If mid is odd
        else if (mid % 2 == 1) {
            if (arr[mid] == arr[mid - 1])
                search(arr, mid + 1, high);
            else
                search(arr, low, mid - 1);
        }
    }
 
    // Driver Code
    public static void Main(String[] args)
    {
        int[] arr = { 1, 1, 2, 4, 4, 5, 5, 6, 6 };
        search(arr, 0, arr.Length - 1);
    }
}
 
// This code is contributed by Nitin Mittal.


PHP
 $high)
        return;
 
    if ($low==$high)
    {
        echo("The required element is " );
        echo $arr[$low] ;
        return;
    }
 
    // Find the middle point
    $mid = ($low + $high) / 2;
 
    // If mid is even and element
    // next to mid is same as mid,
    // then output element lies on
    // right side, else on left side
    if ($mid % 2 == 0)
    {
        if ($arr[$mid] == $arr[$mid + 1])
            search($arr, $mid + 2, $high);
        else
            search($arr, $low, $mid);
    }
     
    // If mid is odd
    else
    {
        if ($arr[$mid] == $arr[$mid - 1])
            search($arr, $mid + 1, $high);
        else
            search($arr, $low, $mid - 1);
    }
}
 
    // Driver Code
    $arr = array(1, 1, 2, 4, 4, 5, 5, 6, 6);
    $len = sizeof($arr);
    search($arr, 0, $len - 1);
 
// This code is contributed by nitin mittal
?>


Javascript


输出

The required element is 2

时间复杂度: O(n)
空间复杂度:O(1)

另一个简单的解决方案是使用XOR (a ^ a = 0 & a ^ 0 = a) 的属性。这个想法是找到完整数组的异或。数组的XOR是必需的答案。

下面是上述方法的实现。

C++

// C++ program to find the element that
// appears only once
#include 
using namespace std;
 
// A XOR based function to find
// the element that appears only once
void search(int arr[], int n)
{
    int XOR = 0;
    for (int i = 0; i < n; i++) {
        XOR = XOR ^ arr[i];
    }
    cout << "The required element is " << XOR << "\n";
}
 
// Driver code
int main()
{
    int arr[] = { 1, 1, 2, 4, 4, 5, 5, 6, 6 };
    int len = sizeof(arr) / sizeof(arr[0]);
 
    search(arr, len);
 
    return 0;
}
 
// This code is contributed by yashbeersingh42

Java

// Java program to find the element that
// appears only once
import java.io.*;
 
class GFG {
    // A XOR based function to find
    // the element that appears only once
    static void search(int arr[], int n)
    {
        int XOR = 0;
        for (int i = 0; i < n; i++) {
            XOR = XOR ^ arr[i];
        }
        System.out.println("The required element is "
                           + XOR);
    }
    // Driver Code
    public static void main(String[] args)
    {
        int arr[] = { 1, 1, 2, 4, 4, 5, 5, 6, 6 };
        int len = arr.length;
 
        search(arr, len);
    }
}
 
// This code is contributed by yashbeersingh42

蟒蛇3

# Python3 program to find the element that
# appears only once
 
# A XOR based function to find
# the element that appears only once
def search(arr, n) :
 
    XOR = 0
    for i in range(n) :
        XOR = XOR ^ arr[i]
 
    print("The required element is", XOR)
 
# Driver code
arr = [ 1, 1, 2, 4, 4, 5, 5, 6, 6 ]
Len = len(arr)
 
search(arr, Len)
 
# This code is contributed by divyesh072019

C#

// C# program to find the element that
// appears only once
using System;
 
class GFG{
     
// A XOR based function to find
// the element that appears only once
static void search(int []arr, int n)
{
    int XOR = 0;
     
    for(int i = 0; i < n; i++)
    {
        XOR = XOR ^ arr[i];
    }
    Console.Write("The required element is " + XOR);
}
 
// Driver Code
public static void Main(String[] args)
{
    int []arr = { 1, 1, 2, 4, 4, 5, 5, 6, 6 };
    int len = arr.Length;
     
    search(arr, len);
}
}
 
// This code is contributed by shivanisinghss2110

Javascript


输出
The required element is 2

时间复杂度: O(n)
空间复杂度: O(1)

一个高效的解决方案可以在 O(Log n) 时间内找到所需的元素。这个想法是使用二分搜索。下面是对输入数组的观察。
required 之前的所有元素第一次出现在偶数索引 (0, 2, ..) 和下一次出现在奇数索引 (1, 3, …)。并且所需元素之后的所有元素第一次出现在奇数索引处,下一次出现在偶数索引处。
1)找到中间索引,说’mid’。
2) 如果 ‘mid’ 是偶数,则比较 arr[mid] 和 arr[mid + 1]。如果两者相同,则在 ‘mid’ 之后和其他在 mid 之前的所需元素。
3) 如果 ‘mid’ 是奇数,则比较 arr[mid] 和 arr[mid – 1]。如果两者相同,则在 ‘mid’ 之后和其他在 mid 之前的所需元素。

下面是基于上述思想的实现:

C++

// C++ program to find the element that
// appears only once
#include 
using namespace std;
 
// A Binary Search based function to find
// the element that appears only once
void search(int arr[], int low, int high)
{
 
    // Base cases
    if (low > high)
        return;
 
    if (low == high) {
        cout << "The required element is " << arr[low];
        return;
    }
 
    // Find the middle point
    int mid = (low + high) / 2;
 
    // If mid is even and element next to mid is
    // same as mid, then output element lies on
    // right side, else on left side
    if (mid % 2 == 0) {
        if (arr[mid] == arr[mid + 1])
            search(arr, mid + 2, high);
        else
            search(arr, low, mid);
    }
 
    // If mid is odd
    else {
        if (arr[mid] == arr[mid - 1])
            search(arr, mid + 1, high);
        else
            search(arr, low, mid - 1);
    }
}
 
// Driver code
int main()
{
    int arr[] = { 1, 1, 2, 4, 4, 5, 5, 6, 6 };
    int len = sizeof(arr) / sizeof(arr[0]);
 
    search(arr, 0, len - 1);
 
    return 0;
}
 
// This code is contributed by ShubhamCoder

C

// C program to find the element that appears only once
#include 
 
// A Binary Search based function to find the element
// that appears only once
void search(int* arr, int low, int high)
{
    // Base cases
    if (low > high)
        return;
 
    if (low == high) {
        printf("The required element is %d ", arr[low]);
        return;
    }
 
    // Find the middle point
    int mid = (low + high) / 2;
 
    // If mid is even and element next to mid is
    // same as mid, then output element lies on
    // right side, else on left side
    if (mid % 2 == 0) {
        if (arr[mid] == arr[mid + 1])
            search(arr, mid + 2, high);
        else
            search(arr, low, mid);
    }
    else // If mid is odd
    {
        if (arr[mid] == arr[mid - 1])
            search(arr, mid + 1, high);
        else
            search(arr, low, mid - 1);
    }
}
 
// Driver code
int main()
{
    int arr[] = { 1, 1, 2, 4, 4, 5, 5, 6, 6 };
    int len = sizeof(arr) / sizeof(arr[0]);
    search(arr, 0, len - 1);
    return 0;
}

Java

// Java program to find the element that appears only once
 
public class Main {
    // A Binary Search based method to find the element
    // that appears only once
    public static void search(int[] arr, int low, int high)
    {
        if (low > high)
            return;
        if (low == high) {
            System.out.println("The required element is "
                               + arr[low]);
            return;
        }
 
        // Find the middle point
        int mid = (low + high) / 2;
 
        // If mid is even and element next to mid is
        // same as mid, then output element lies on
        // right side, else on left side
        if (mid % 2 == 0) {
            if (arr[mid] == arr[mid + 1])
                search(arr, mid + 2, high);
            else
                search(arr, low, mid);
        }
        // If mid is odd
        else if (mid % 2 == 1) {
            if (arr[mid] == arr[mid - 1])
                search(arr, mid + 1, high);
            else
                search(arr, low, mid - 1);
        }
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        int[] arr = { 1, 1, 2, 4, 4, 5, 5, 6, 6 };
        search(arr, 0, arr.length - 1);
    }
}
// This code is contributed by Tanisha Mittal

Python

# A Binary search based function to find
# the element that appears only once
 
 
def search(arr, low, high):
 
    # Base cases
    if low > high:
        return None
 
    if low == high:
        return arr[low]
 
    # Find the middle point
    mid = low + (high - low)/2
 
    # If mid is even and element next to mid is
    # same as mid, then output element lies on
    # right side, else on left side
    if mid % 2 == 0:
 
        if arr[mid] == arr[mid+1]:
            return search(arr, mid+2, high)
        else:
            return search(arr, low, mid)
 
    else:
        # if mid is odd
        if arr[mid] == arr[mid-1]:
            return search(arr, mid+1, high)
        else:
            return search(arr, low, mid-1)
 
# Driver Code
# Test Array
arr = [1, 1, 2, 4, 4, 5, 5, 6, 6]
 
# Function call
result = search(arr, 0, len(arr)-1)
 
if result is not None:
    print "The required element is %d" % result
else:
    print "Invalid Array"

C#

// C# program to find the element
// that appears only once
using System;
 
class GFG {
 
    // A Binary Search based
    // method to find the element
    // that appears only once
    public static void search(int[] arr, int low, int high)
    {
 
        if (low > high)
            return;
        if (low == high) {
            Console.WriteLine("The required element is "
                              + arr[low]);
            return;
        }
 
        // Find the middle point
        int mid = (low + high) / 2;
 
        // If mid is even and element
        // next to mid is same as mid
        // then output element lies on
        // right side, else on left side
        if (mid % 2 == 0) {
            if (arr[mid] == arr[mid + 1])
                search(arr, mid + 2, high);
            else
                search(arr, low, mid);
        }
 
        // If mid is odd
        else if (mid % 2 == 1) {
            if (arr[mid] == arr[mid - 1])
                search(arr, mid + 1, high);
            else
                search(arr, low, mid - 1);
        }
    }
 
    // Driver Code
    public static void Main(String[] args)
    {
        int[] arr = { 1, 1, 2, 4, 4, 5, 5, 6, 6 };
        search(arr, 0, arr.Length - 1);
    }
}
 
// This code is contributed by Nitin Mittal.

PHP

 $high)
        return;
 
    if ($low==$high)
    {
        echo("The required element is " );
        echo $arr[$low] ;
        return;
    }
 
    // Find the middle point
    $mid = ($low + $high) / 2;
 
    // If mid is even and element
    // next to mid is same as mid,
    // then output element lies on
    // right side, else on left side
    if ($mid % 2 == 0)
    {
        if ($arr[$mid] == $arr[$mid + 1])
            search($arr, $mid + 2, $high);
        else
            search($arr, $low, $mid);
    }
     
    // If mid is odd
    else
    {
        if ($arr[$mid] == $arr[$mid - 1])
            search($arr, $mid + 1, $high);
        else
            search($arr, $low, $mid - 1);
    }
}
 
    // Driver Code
    $arr = array(1, 1, 2, 4, 4, 5, 5, 6, 6);
    $len = sizeof($arr);
    search($arr, 0, $len - 1);
 
// This code is contributed by nitin mittal
?>

Javascript


输出
The required element is 2

时间复杂度: O(Log n)
注意:这个问题其他的解决方案的办法在这篇文章中讨论的细微变化。

如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程学生竞争性编程现场课程