在一個長度為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;
}

思路:先排序,然后統計計算


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



猜您在找 劍指Offer(Java版)第五十六題:在一個長度為n的數組里的所有數字都在0到n-1的范圍內。 數組中某些數字是重復的,但不知道有幾個數字是重復的。 也不知道每個數字重復幾次。請找出數組中任意一個重復的數字。 例如,如果輸入長度為7的數組{2,3,1,0,2,5,3},那么對應的輸出是第一個重復的數字2。 面試題3:在一個長度為n的數組里的所有數字都在0到n-1的范圍內。 數組中某些數字是重復的,但不知道有幾個數字是重復的。也不知道每個數字重復幾次。請找出數組中任意一個重復的數字。 例如,如果輸入長度為7的數組{2,3,1,0,2,5,3},那么對應的輸出是第一個重復的數字2。 在一個長度為n的數組里的所有數字都在0到n-1的范圍內。 數組中某些數字是重復的,但不知道有幾個數字是重復的。也不知道每個數字重復幾次。請找出數組中任意一個重復的數字。 例如,如果輸入長度為7的數組{2,3,1,0,2,5,3},那么對應的輸出是重復的數字2或者3。 劍指offer(Java版)第一題:在一個長度為n的數組里的所有數字都在0到n-1的范圍內。 數組中某些數字是重復的,但不知道有幾個數字重復了,也不知道每個數字重復了幾次。 *請找出數組中任意一個重復的數字。 *例如,如果輸入長度為7的數組{2, 3, 1, 0, 2, 5, 3},那么對應的輸出是重復的數字2或者3。 面試題:給定一個長度為N的數組,其中每個元素的取值范圍都是1到N。判斷數組中是否有重復的數字 找出數組中重復的數字 1、找出數組中重復的數字 找出數組中重復的數字 數組中重復的數字 如何把一個整型數組中重復的數字去掉
 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM