• 在一个长度为n的数组里的所有数字都在0到n-1的范围内。 数组中某些数字是重复的,但不知道有几个数字是重复的。也不知道每个数字重复几次。请找出数组中任意一个重复的数字。 例如,如果输入长度为7的数组{2,3,1,0,2,5,3},那么对应的输出是重复的数字2或者3


    // test14.cpp : 定义控制台应用程序的入口点。
    //

    #include "stdafx.h"
    #include<iostream>
    #include<string>
    #include<cctype>
    #include <vector>
    #include<exception>
    #include <initializer_list>
    using namespace std;
    
    class Solution {
    public:
    	// Parameters:
    	//numbers: an array of integers
    	//length:  the length of array numbers
    	//duplication: (Output) the duplicated number in the array number
    	// Return value:   true if the input is valid, and there are some duplications in the array number
    	// otherwise false
    	bool duplicate(int numbers[], int length, int* duplication) {
    		
    		int k = 0;//统计duplication数组中的元素个数
    		bool result = false; //返回结果
    
    		//对numbers数组进行排序
    		for (int i = 0; i < length; i++)
    		{
    			for (int j = i+1; j < length; j++)
    			{
    				if (numbers[i] > numbers[j])
    				{
    					int t = numbers[j];
    					numbers[j] = numbers[i];
    					numbers[i] = t;
    				}
    			}
    
    		}
    
    		//cout << "numbers:";
    		//for (int i = 0; i < length; i++)
    		//{
    		//	cout << numbers[i] << "  ";
    		//}
    		//cout << endl;
    
    		int temp = numbers[0];
    
    		for (int i = 1; i < length; i++)
    		{
    			if (temp == numbers[i])//如果有重复
    			{
    			   if(k==0)//duplication中没有数据进行的处理
    				{
    					duplication[k++] = temp;
    					result = true;
    				}
    				
    				else if (temp != duplication[k - 1])//duplication中有数据要进行的判断,如果没有存储,需要存储
    				{
    					duplication[k++] = temp;
    					result = true;
    				}
    				else // duplication中有数据要进行的判断,如果已经存储,不需要做处理
    				{
    					result = true;
    				}
    					
    			}
    			else//如果和之前数据没有相同的,temp等于这个数据
    			{
    				temp = numbers[i];
    			}
    
    		}
    		
    	/*	cout << "duplication:";
    		for (int i = 0; i < k; i++)
    		{
    			cout << duplication[i] << "  ";
    		}
    		cout << endl;*/
    
    		return result;
    
    	}
    };
    
    int main()
    {
    	int a[7] = { 2,3,1,0,2,5,3 };
    	int b[7] = { 0 };
    	int* duplication=b;
    	Solution so;
    	so.duplicate(a, 7, duplication);
    	
    	return 0;
    }
    
    思路:先排序,然后统计计算
  • 相关阅读:
    [转]google gflags 库完全使用
    机器学习者面试,看这10个建议
    分享10个数据分析的小技巧(Python)
    工作学习上实用的编程相关知识分享
    前端React 框架- UmiJS有听说过吗?
    PyTorch如何构建深度学习模型?
    Sigmoid 和 Softmax 如何进行函数处理分类?
    从零开始学习机器学习最简单的 kNN 算法
    监督学习中的决策树算法(含代码)
    可视化Bert网络,发掘其中真实世界的嵌入
  • 原文地址:https://www.cnblogs.com/wdan2016/p/5938691.html
Copyright © 2020-2023  润新知