本周心得
vector中,字符串的sort()排序问题(按顺序以字母表比较,前一位优先级高:abc < acb < bca)
数组中的排序sort问题:(sort函数作用范围为 [begin, end) ,不包含最后一位 ) 静态数组:int a[10] = { 9, 0, 1, 2, 3, 7, 4, 5, 8, 6 }; sort(a, a +10); (注意加的是长度,加到数组末尾的下一位) vector: sort(heights.begin(), heights.end()); (vector中的end()代表的是最后一位数的下一位)
string.substr(int start_index, int length)的用法: 两个参数时,第一个是起始位置,第二个是子串长度 eg: substr(0,5)获得字符串s中 从第0位开始的长度为5的字符串 一个参数时默认从指定开始位置到尾 eg: substr(1) ) 获得字符串s中 从第1位开始的到结尾的字符串
char字符串数组是以 ‘\0’ 为结尾的,但是string 是一个类,结尾没有字符’\0’
C++删除string最后一个字符的几种方法: - str.pop_back(); - str.erase(str.end() - 1); - str = str.substr(0, str.length() - 1);
string.erase()的用法 (1)erase(pos,n); 删除从pos开始的n个字符,比如erase(0,1)就是删除第一个字符 (2) erase(pos); 删除从pos开始的到结尾的字符,比如erase(0)就是删除第一个字符后所有元素 (3)erase(first, last);删除从first到 last之间(last不会删除)的字符(first和last都是迭代器)且返回last迭代器 (4)erase(first);删除pos处的一个字符(first是迭代器)且返回删除元素的下一个迭代器
寻找质数的算法:厄拉多塞筛法(精简高效寻找每个数字的倍数的算法)
关于字符的转码问题: char to int : 一般使用 char - ‘0’ int to cha : 一般使用 int + ‘0’ (注意: char(4) : 将4转变为’\4’而不是 字符 ‘4’,int(‘a’): 将字符串转换为对应的ASCII码 因此涉及int/char转换问题最好使用 ±’0’,其中 (char) 绝对不要使用!)
判断vector中有无某值:(STL)find vector<int>::iterator it = find(arr.begin(),arr.end(),res);
if( it != arr.end() ) //值在数组中
if( it == arr.end() ) //值不在数组中
弗洛伊德循环查找算法 (快慢指针法/龟兔指针法) 原理:兔子每走一步就向乌龟靠近一个节点(在它们的移动方向上)。若有则必相遇 用于判断一个链表是否有循环
594,最长和谐子序列
class Solution {
public :
int findLHS ( vector< int > & nums) {
unordered_map< int , int > hash;
for ( auto num: nums)
hash[ num] ++ ;
int res = 0 ;
for ( auto i : hash)
if ( hash. count ( i. first+ 1 ) )
res = max ( res, i. second + hash[ i. first + 1 ] ) ;
return res;
}
} ;
1160, 拼写单词
class Solution {
public :
int countCharacters ( vector< string> & words, string chars) {
int res= 0 ;
int ch[ 26 ] = {
0 } ;
for ( char c: chars)
ch[ c- 'a' ] ++ ;
for ( string word: words)
{
int wd[ 26 ] = {
0 } ;
for ( char c: word)
wd[ c- 'a' ] ++ ;
res+ = word. size ( ) ;
for ( char c: word)
{
if ( ch[ c- 'a' ] < wd[ c- 'a' ] )
{
res- = word. size ( ) ;
break ;
}
}
}
return res;
}
} ;
572, 分糖果
class Solution {
public :
int distributeCandies ( vector< int > & candies) {
int nums = candies