Sword Finger Offer Question 40
The topic is as follows
Idea and code
Hash table (nothing to say)
Map++ when you encounter it, and then check the table only once and store it in, but in the end you have to sort it out
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param array int整型vector
* @return int整型vector
*/
vector<int> FindNumsAppearOnce(vector<int>& array) {
// write code here
map<int,int>mp;
int len=array.size();
for(int i=0;i<len;i++){
mp[array[i]]++;
}
vector<int>v;
for(int i=0;i<len;i++){
if(mp[array[i]]==1) v.push_back(array[i]);
}
if(v[0]>v[1]) swap(v[0],v[1]);
return v;
}
};
Sort first and then find
After sorting, if it appears multiple times, it will be connected together, just look for the front and back.
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param array int整型vector
* @return int整型vector
*/
vector<int> FindNumsAppearOnce(vector<int>& array) {
// write code here
sort(array.begin(),array.end());
vector<int> c;
for(int i=0;i<array.size();i++){
if(i-1<0){
if(array[0]!=array[1]) c.push_back(array[0]);
}else{
if(array[i-1]!=array[i]&&array[i]!=array[i+1])
c.push_back(array[i]);
else if(i+1==array.size()&&array.size()&&array[array.size()-1]!=array[array.size()-2])
c.push_back(array[array.size()-1]);
}
if(c.size()==2) break;
}
return c;
}
};