1. 把字符串转换成整数
class Solution {
public:
int StrToInt(string str) {
if(str.empty()) return 0;
int nums=0, flag=1;
if(str[0]=='-') flag=-1;
else if(str[0]=='+') nums=0;
else if(str[0]>='0' and str[0]<='9') nums=str[0]-'0';
else return 0;
for(int i=1;i<str.length();i++){
if(str[i]<'0' or str[i]>'9') return 0;
//nums=nums*10+str[i]-'0';
//(nums<<1)+(nums<<3)=(nums*2)+(nums*8)
//(str[i]&0xf):0xf=00001111,按Ascii码的二进制按位与
nums=(nums<<1)+(nums<<3)+(str[i]&0xf);
}
return flag*nums;
}
};
2. 数组中重复的数字
桶排序的思想,空间占用较多,因为创了新的vector
class Solution {
public:
// Parameters:
// numbers: an array of integers
// length: the length of array numbers
// duplication: (Output) the duplicated number in the array number
// Return value: true if the input is valid, and there are some duplications in the array number
// otherwise false
bool duplicate(int numbers[], int length, int* duplication) {
if(length<=1) return false;
vector<int> nums(length,0);
for(int i=0;i<length;i++){
if(nums[numbers[i]]){
*duplication=numbers[i];
return true;
}
nums[numbers[i]]++;
}
return false;
}
};
书上的解题思路,不添加新数组,将nums[i]换到nums[nums[i]]的位置上,当发现位置上已经有一个正确的数时就找到了重复值
class Solution {
public:
bool duplicate(int numbers[], int length, int* duplication) {
if(length<=1) return false;
for(int i=0;i<length;i++){
int temp;
if(numbers[i]!=i){
if(numbers[numbers[i]]==numbers[i]){
*duplication=numbers[i];
return true;
}
else{
temp=numbers[i];
numbers[i]=numbers[temp];
numbers[temp]=temp;
}
}
}
return false;
}
};
3. 二维数组的查找
class Solution {
public:
bool Find(int target, vector<vector<int> > array) {
int xbegin=0,xend=array.size()-1;
int ybegin=0,yend=array[0].size()-1;
if(xend<0 or yend<0) return false;
if(target>array[xend][yend] or target<array[0][0]) return false;
//缩小行的范围
while(xbegin<xend){
if(target<array[xend][0]) xend--;
else if(target>array[xbegin][yend]) xbegin++;
else break;
}
//缩小列的范围
while(ybegin<yend){
if(target<array[xbegin][yend]) yend--;
else if(target>array[xend][ybegin]) ybegin++;
else break;
}
for(int i=xbegin;i<=xend;i++){
for(int j=ybegin;j<=yend;j++){
if(array[i][j]==target) return true;
}
}
return false;
}
};
4. 替换空格
从后往前替换。
class Solution {
public:
void replaceSpace(char *str,int length) {
//length 代表str空间的总长度但不是所含内容的总长度
if(length<=0||str==nullptr) return;
int count=0,old=0,m=0;
while(str[m]!='\0'){
old++;
if(str[m]==' ') {
count++;
}
m++;
}
if(count==0 or (count*2+old)>length) return;
else{
//不要减一是因为末尾有‘\0’
int j=old;
int i=count*2+old;
while(j>=0 and i>=0){
if(str[j]!=' '){
str[i--]=str[j];
}
else {
str[i--]='0';
str[i--]='2';
str[i--]='%';
}
j--;
}
}
}
};
5. 从尾到头打印链表
用栈的方式。
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
vector <int> result;
if(head==NULL) return result;
stack<ListNode*> stk;
ListNode* node=head;
while(node!=NULL){
stk.push(node);
node=node->next;
}
while(!stk.empty()){
node=stk.top();
result.push_back(node->val);
stk.pop();
}
return result;
}
};