ProDeveloperTutorial.com

教程和编程解决方案
菜单
  • Shell脚本
  • 系统设计
  • Linux系统编程
  • 4g LTE
  • 编码问题
  • C
  • C ++
  • DSA
  • GIT

给定一个数组,检查它是否有重复的元素,CPP中有2个解决方案

前开发者教程 二月11,2019

如果数组具有重复项,则输出应为true,否则,如果所有数组元素都是唯一的,则返回false。

例:

Input: [1, 2, 3, 1]

Output: True

Input:[1, 2, 3, 4]

Output:  False

 

方法1:通过使用set。

众所周知,set仅包含唯一元素。因此,我们将数组的所有元素插入到集合中,并检查原始长度和集合的长度是否相同。如果相同,则所有元素都是唯一的,否则我们有重复的元素。

方法2:通过排序。

我们对给定的数组进行排序,然后检查present元素和next元素。如果它们相同,则返回true,否则返回false。继续直到数组的结尾。

C ++解决方案

#include<iostream>
#include<string>
#include<set>
#include<vector>

using namespace std;



bool check_duplicate_method_1(vector<int>& array) 
{
        return set<int>(array.begin(), array.end()).size() < array.size();
}

bool check_duplicate_method_2(vector<int>& array)
{

	sort(array.begin(), array.end());

    for (int i=0; i<int(array.size())-1; i++) 
    {
        if (array[i]==array[i+1])
            return true;
    }
    return false;   
}





int main()
{
	//test case 1
	vector<int> array = {1, 2, 3, 1};

	//test case 2
	//vector<int> array = {1, 2, 3};


	if(check_duplicate_method_1(array))
		cout<<"The array has duplicate elements.[method_1]"<<endl;
	else
		cout<<"The array does not has duplicate elements.[method_1]"<<endl;


	if(check_duplicate_method_2(array))
		cout<<"The array has duplicate elements.[method_2]"<<endl;
	else
		cout<<"The array does not has duplicate elements.[method_2]"<<endl;

	return 0;
}

输出:

The array has duplicate elements.[method_1]

The array has duplicate elements.[method_2]

 

 

 

分享
电子邮件
鸣叫
领英
Reddit
绊倒
Pinterest的
上一篇文章
下一篇

关于作者

前开发者教程

每天我们都会讨论竞争性编程问题,请加入我们的网站:   电报频道

ProDeveloperTutorial.com

教程和编程解决方案
版权© 2020 ProDeveloperTutorial.com
从以下课程获得热门课程: 教育性的
    <kbd id="dB1CAs8"></kbd>

      <small id="JExAmmN"><a id="LYxbjV0" class="LGbTHTw"><strike id="WupJdp3"></strike></a></small>

    1. <canvas id="mk6uBZl" class="mHMpJmZ"></canvas>



        1. <frameset id="SOagvl2"></frameset>