sort()是常用于数组和字符串中的排序函数,使用的排序方法是类似于快排的方法,时间复杂度为n*log2(n),效率较高。使用时需引入头文件#include <algorithm>
#include <algorithm>
sort(_name.begin(),_name.end(),less<data_type>())无返回值,修改_name自身。
(1)第一个参数是要排序的数组的起始地址。
(2)第二个参数是结束的地址(最后一位要排序的地址)
(3)第三个参数是排序的方法,默认是从小到大排序,反之用grater<data_type>().
巧用sort:
判断字符串中的若干个元素是否两两相同,正常情况需要分情况一组一组对比,此时可以使用sort(_name)函数进行排序,此时便不需要在进行分情况。
如该题目:
一般求解代码:
#include <iostream>
using namespace std;
int main()
{
int T;
cin >> T;
for (int i = T; i > 0; i--)
{
string a;
cin >> a;
if (a[0] == a[1] && a[1] == a[2] && a[0] != a[3]) { cout << "Yes"; }
else if (a[0] == a[1] && a[1] == a[3] && a[0] != a[2]) { cout << "Yes"; }
else if (a[0] == a[2] && a[2] == a[3] && a[0] != a[1]) { cout << "Yes"; }
else if (a[1] == a[2] && a[2] == a[3] && a[1] != a[0]) { cout << "Yes"; }
else { cout << "No"; }cout << endl;
}
}
使用sort()函数:
排序后,若符合情况,则相同的三张在前,或者在后;此时只需要求第一张与第四张不相同,第一张与第三张相同或者第二张与第四张相同即可。代码如下:
#include <iostream>
#include <algorithm>
using namespace std;
int main2()
{
int T;
cin >> T;
for (int i = 0; i <= T; i++)
{
string s;
cin >> s;
sort(s.begin(), s.end());
if (s[0] != s[3] && (s[1] == s[3] || s[0] == s[2]))
cout<<"Yes";
else cout<<"No";
}
return 0;
}