[Offer] wins the array of numbers appears only once (the number of occurrences statistics of each array numbers)

Offer to prove safety before doing this problem, we first look at the following statistics array digital title number of occurrences.

Count the number of times each number appears array

Use count, the return is to find the number of elements. If so, return 1; otherwise, it returns 0.
Note that, map does not exist in the same element, so the return value can only be 1 or 0.
Use find, return is find elements of position, no map.end returns ().

void EleCount(vector<int> data) {
	int len = data.size();
	map<int, int > Mymap;
	for (int i = 0; i < len; ++i) {
		if (Mymap.find(data[i]) != Mymap.end()) {
//使用find,返回的是被查找元素的位置,没有则返回map.end()。
			Mymap[data[i]]++;
		}
		else
			Mymap.insert(pair<int, int>(data[i], 1));
	}
	for (auto it : Mymap)
	//auto 下面会解释
		cout << it.first << " : " << it.second << endl;

}

Application of the auto in the STL

vector<int>vect;
方法一:

for(auto it = vect.begin(); it != vect.end(); ++it)

{ //it的类型是vector<int>::iterator

cout << *it;

}

方法二:

for(auto it : vect)

{

cout << it;

}

This new feature is c ++ 11, the scope for, the equivalent of java for each. vect is a container or a traversable stream, such as vector type, IT can be used to obtain each of the container elements during traversal.
----------------
Original link: https: //blog.csdn.net/weirdo_coder/article/details/86716322

A figure below the statistical list appears only

Title describes
an array of integers in addition to the two figures, other figures appear twice. Please write a program to find these two figures appear only.

Ideas:
1- statistics of each map with a number of occurrences vessel
2- traverse map container 1, the number of occurrences equal to the output;

Note: The above statistics only slightly modified code on the line

void FindNumsAppearOnce(vector<int> data, int* num1, int* num2) {
		int len = data.size();
		
		map<int, int>mymap;
		for (int i = 0; i < len; i++) {
			if (mymap.end() != mymap.find(data[i]))
				mymap[data[i]]++;
			else
				mymap.insert(pair<int, int>(data[i], 1));
		}
		*num1 = *num2 = 0;
		for(auto it :mymap){
			if(it.second==1){
				if(*num1!=0)
					*num2=it.first;
				else
					*num1=it.first;
				}
		}
}

Traversal can also be modified to use an iterator:

for (map<int, int>::iterator it = mymap.begin(); it!=mymap.end();it++) {

		if ((*it).second == 1){
			if (*num1 != 0)
				*num2 = ((*it).first);
			else
				*num1 = (*it).first;
		}
	}

Test Case

int main() {
	vector<int> data;
	int a[10] = { 1,2,3,4,5,4,3,1,2,6 };
	for ( int i = 0; i < 10; ++i) {
		data.push_back(a[i]);
	}
	EleCount(data);
	FindNumsAppearOnce(data, &data[0], &data[1]);
	cout << data[0] <<" "<< data[1] << endl;
}

Here Insert Picture Description

Published 57 original articles · won praise 28 · views 4117

Guess you like

Origin blog.csdn.net/weixin_41747893/article/details/104632298