📌  相关文章
📜  在不使用条件运算符的情况下从数组中查找最大元素

📅  最后修改于: 2021-05-25 07:12:49             🧑  作者: Mango

给定一个n元素数组,我们必须在其中不使用任何条件运算符(例如大于或小于)的情况下找到其中最大的元素。

例子:

Input : arr[] = {5, 7, 2, 9}
Output : Largest element = 9

Input : arr[] = {15, 0, 2, 15}
Output : Largest element = 15

第一种方法(散列的使用):要从数组中找到最大的元素,我们可以使用散列的概念,即应维护所有元素的散列表,然后在处理完所有数组元素之后,我们应通过以下方式在散列中找到最大的元素:只需从末尾遍历哈希表。

但是这种方法有一些缺点,例如在非常大的元素保持哈希表是不可能或不可行的情况下。

更好的方法(按位AND的使用):最近,我们学习了如何从给定数组中找到最大的AND值对。同样,我们知道,如果我们将任何数字与INT_MAX(所有位都设置为位)进行按位与,则结果将是该数字本身。现在,使用此属性,我们将尝试从数组中查找最大的元素,而不使用任何大于或小于等条件运算符。

为了找到最大的元素,我们将首先在数组中插入一个额外的元素,即INT_MAX,然后,我们将尝试从数组中查找任何一对的最大AND值。获得的最大值将包含INT_MAX的AND值和原始数组的最大元素,这是我们要求的结果。

下面是上述方法的实现:

C++
// C++ Program to find largest element from array
#include 
using namespace std;
  
// Utility function to check number of 
// elements having set msb as of pattern
int checkBit(int pattern, vector arr, int n)
{
    int count = 0;
    for (int i = 0; i < n; i++)
        if ((pattern & arr[i]) == pattern)
            count++;
    return count;
}
  
// Function for finding maximum and value pair
int largest(int arr[], int n)
{
    // Create a vector of given array
    vector v(arr, arr + n);
  
    // Insert INT_MAX and update n
    v.push_back(INT_MAX);
    n++;
  
    int res = 0;
  
    // Iterate over total of 30bits from
    // msb to lsb
    for (int bit = 31; bit >= 0; bit--) 
    {
  
        // Find the count of element having set msb
        int count = checkBit(res | (1 << bit), v, n);
  
        // if count | 1 != 1 set particular 
        // bit in result
        if ((count | 1) != 1)
            res |= (1 << bit);
    }
  
    return res;
}
  
// Driver Code
int main()
{
    int arr[] = { 4, 8, 6, 2 };
    int n = sizeof(arr) / sizeof(arr[0]);
    cout << "Largest element = " << largest(arr, n);
    return 0;
}


Java
// Java Program to find largest element from array
import java.util.Vector;
import java.util.Arrays;
  
class GfG 
{
  
// Utility function to check number of 
// elements having set msb as of pattern
static int checkBit(int pattern, Vector arr, int n)
{
    int count = 0;
    for (int i = 0; i < n; i++)
        if ((pattern & arr.get(i)) == pattern)
            count++;
    return count;
}
  
// Function for finding maximum and value pair
static int largest(int arr[], int n)
{
    // Create a vector of given array
    Vector v = new Vector<>();
    for(Integer a:arr)
        v.add(a);
  
    // Insert INT_MAX and update n
    v.add(Integer.MAX_VALUE);
    n++;
  
    int res = 0;
  
    // Iterate over total of 30bits from
    // msb to lsb
    for (int bit = 31; bit >= 0; bit--) 
    {
  
        // Find the count of element having set msb
        int count = checkBit(res | (1 << bit), v, n);
  
        // if count | 1 != 1 set particular 
        // bit in result
        if ((count | 1) != 1)
            res |= (1 << bit);
    }
  
    return res;
}
  
// Driver Code
public static void main(String[] args) 
{
    int arr[] = { 4, 8, 6, 2 };
    int n = arr.length;
    System.out.println("Largest element = " + 
                            largest(arr, n));
}
}
  
/* This code contributed by PrinciRaj1992 */


Python3
# Python3 Program to find largest 
# element from array
import math as mt
  
# Utility function to check number of 
# elements having set msb as of pattern
def checkBit(pattern, arr, n):
    count = 0
    for i in range(n):
        if ((pattern & arr[i]) == pattern):
            count += 1
    return count
  
# Function for finding maximum 
# and value pair
def largest(arr, n):
  
    # Create a vector of given array
    v = arr
  
    # Insert max value of Int and update n
    v.append(2**31 - 1)
    n = n + 1
  
    res = 0
  
    # Iterate over total of 30bits
    # from msb to lsb
    for bit in range(31, -1, -1):
  
        # Find the count of element 
        # having set msb
        count = checkBit(res | (1 << bit), v, n)
  
        # if count | 1 != 1 set particular
        # bit in result
        if ((count | 1) != 1):
            res |= (1 << bit)
      
    return res
  
# Driver Code
arr = [4, 8, 6, 2] 
n = len(arr)
print("Largest element =", largest(arr, n))
  
# This code is contributed by
# Mohit kumar 29


C#
// C# Program to find largest element from array
using System;    
using System.Collections.Generic;    
  
class GfG 
{
   
// Utility function to check number of 
// elements having set msb as of pattern
static int checkBit(int pattern, List arr, int n)
{
    int count = 0;
    for (int i = 0; i < n; i++)
        if ((pattern & arr[i]) == pattern)
            count++;
    return count;
}
   
// Function for finding maximum and value pair
static int largest(int []arr, int n)
{
    // Create a vector of given array
    List v = new List();
    foreach(int a in arr)
        v.Add(a);
   
    // Insert INT_MAX and update n
    v.Add(int.MaxValue);
    n++;
   
    int res = 0;
   
    // Iterate over total of 30bits from
    // msb to lsb
    for (int bit = 31; bit >= 0; bit--) 
    {
   
        // Find the count of element having set msb
        int count = checkBit(res | (1 << bit), v, n);
   
        // if count | 1 != 1 set particular 
        // bit in result
        if ((count | 1) != 1)
            res |= (1 << bit);
    }
   
    return res;
}
   
// Driver Code
public static void Main(String[] args) 
{
    int []arr = { 4, 8, 6, 2 };
    int n = arr.Length;
    Console.WriteLine("Largest element = " + 
                            largest(arr, n));
}
}
  
// This code contributed by Rajput-Ji


PHP
= 0; $bit--)
    {
  
        // Find the count of element 
        // having set msb
        $count = checkBit($res | (1 << $bit),$arr, $n);
  
        // if count | 1 != 1 set 
        // particular bit in result
        if ($count | 1 != 1)
            $res |= (1 << $bit);
    }
  
    return $res;
}
  
    // Driver code
    $arr = array( 4, 8, 6, 2 );
    $n = sizeof($arr) / sizeof($arr[0]);
    echo "Largest element = ". largest($arr, $n);
  
// This code is contributed by mits  
?>


输出:

Largest element = 8