把数组排成最小的数
描述:
输入一个正整数数组,把所有的数字拼接起来排成一个数字。打印最小的那个。
思路:
定义一个排序规则,两两比较。mn和nm哪个更小。用字符串存储拼接的字符串。
代码:
bool cmp(string a, string b)
{
string temp1 = a + b;
//cout << temp1 << endl;
string temp2 = b + a;
//cout << temp2 << endl;
return temp1 <temp2;
}
void SortArrforMinNumber(int arr[],int len)
{
vector<string> s;
for (int i = 0; i < len; i++)
{
s.push_back(to_string(arr[i]));
}
sort(s.begin(),s.end(),cmp);
for (int i = 0; i < len; i++)
{
cout << s[i];
}
}
第一个只出现一次的字符
思路:
字符大小为8bit,共256个。那么可以用哈希表存储字符的次数。第一次遍历数组,将次数存储到哈希表中,第二次遍历数组找到哈希表中次数为一的字符。
代码:
//PS 在字符串1中删除字符串2中出现过的字符 也可以用哈希表
//PS 删除字符串中重复的字符 用bool哈希表
//变位词 出现的字母和次数相同。一个哈希表 ,+1 -1操作,
char FindFirstNotRepeatChar(char* str)
{
if (str == NULL)
{
return ' ';
}
const int tablesize = 256;
int hashtable[256];
for (int i = 0; i < tablesize; i++)
{
hashtable[i] = 0;
}
char* p = str;
while (*p != ' ')
{
hashtable[int(*p)]++;
p++;
}
p = str;
while (*p != ' ')
{
if (hashtable[int(*p)] == 1)
return *p;
p++;
}
return ' ';
}