在给定的约束下查找重复项
一个有序数组包含 6 个不同的数字,只有 1 个数字重复了 5 次。所以数组中共有10个数字。仅使用两次比较查找重复的数字。
例子 :
Input: arr[] = {1, 1, 1, 1, 1, 5, 7, 10, 20, 30}
Output: 1
Input: arr[] = {1, 2, 3, 3, 3, 3, 3, 5, 9, 10}
Output: 3
在雅虎问
一个重要的观察是,arr[4] 或 arr[5] 肯定是重复元素的出现。以下是基于此观察的实现。
CPP
// C++ program to find duplicate element under
// given constraints.
#include
using namespace std;
// This function assumes array is sorted, has
// 10 elements, there are total 6 different
// elements and one element repeats 5 times.
int findDuplicate(int a[])
{
if (a[3] == a[4])
return a[3];
else if (a[4] == a[5])
return a[4];
else
return a[5];
}
// Driver code
int main()
{
int a[] = {1, 1, 1, 1, 1, 5, 7, 10, 20, 30};
cout << findDuplicate(a);
return 0;
}
JAVA
// Java program to find duplicate element under
// given constraints.
class Num{
// This function assumes array is sorted, has
// 10 elements, there are total 6 different
// elements and one element repeats 5 times.
static int findDuplicate(int a[])
{
if (a[3] == a[4])
return a[3];
else if (a[4] == a[5])
return a[4];
else
return a[5];
}
// Driver code
public static void main(String[] args)
{
int a[] = {1, 1, 1, 1, 1, 5, 7, 10, 20, 30};
System.out.println(findDuplicate(a));
}
}
//This code is contributed by
//Smitha Dinesh Semwal
Python3
# Python 3 program to find duplicate
# element under given constraints.
# This function assumes array is
# sorted, has 10 elements, there are
# total 6 different elements and one
# element repeats 5 times.
def findDuplicate(a):
if (a[3] == a[4]):
return a[3]
else if (a[4] == a[5]):
return a[4]
else:
return a[5]
# Driver code
a = [1, 1, 1, 1, 1, 5, 7,
10, 20, 30]
print(findDuplicate(a))
# This code is contributed by Smitha Dinesh Semwal
C#
// C# program to find duplicate
// element under given constraints.
using System;
class GFG {
// This function assumes array is
// sorted, has 10 elements, there
// are total 6 different elements
// and one element repeats 5 times.
static int findDuplicate(int []a)
{
if (a[3] == a[4])
return a[3];
else if (a[4] == a[5])
return a[4];
else
return a[5];
}
// Driver code
public static void Main()
{
int []a = {1, 1, 1, 1, 1, 5,
7, 10, 20, 30};
Console.Write(findDuplicate(a));
}
}
// This code is contributed by nitin mittal
PHP
Javascript
输出 :
1