剑指offer第七章&第八章
1.把字符串转换成整数
将一个字符串转换成一个整数,要求不能使用字符串转换整数的库函数。 数值为0或者字符串不是一个合法的数值则返回0
输入描述:
输入一个字符串,包括数字字母符号,可以为空
输出描述:
如果是合法的数值表达则返回该数字,否则返回0
分析:思路在代码里已经体现
1 class Solution { 2 public: 3 int StrToInt(string str) 4 { 5 if(str.empty()) 6 return 0; 7 int symbol = 1;//正负号初始化为1表示正数 8 if(str[0] == '-') 9 {//处理负号 10 symbol = -1;//表示是负数 11 str[0] = '0'; //这里是‘0’ 不是0 12 } 13 else if(str[0] == '+') 14 {//处理正号 15 symbol = 1;//表示是正数 16 str[0] = '0'; 17 } 18 int sum = 0; 19 for(int i=0;i<str.size();++i) 20 { 21 if(str[i] < '0' || str[i] > '9') 22 { 23 sum = 0; 24 break; 25 } 26 sum = sum *10 + str[i] - '0'; 27 } 28 return symbol * sum;//正负号乘以sum,即表示字符串所表示的整数 29 } 30 };
2..数组中重复的数字
在一个长度为n的数组里的所有数字都在0到n-1的范围内。 数组中某些数字是重复的,但不知道有几个数字是重复的。也不知道每个数字重复几次。请找出数组中任意一个重复的数字。
例如,如果输入长度为7的数组{2,3,1,0,2,5,3},那么对应的输出是第一个重复的数字2。
分析:注意到数组中的数字都在0——n-1的范围内。如果没有重复数字,那么排序之后数字i将出现在下标为i的位置
从头到尾依次扫描这个数组中的每个数字。当扫描到下标为i的数字时,首先比较这个数字(m)是不是等于i。如果是,接着扫描下一个数字。如果不是,再拿m和第m个数字比较。如果相等,就找到了一个重复数字。如果不等,就把第i个数字和第m个数字交换,把m放到属于它的位置。接下来重复比较,直到找到重复数字。
1 class Solution { 2 public: 3 // Parameters: 4 // numbers: an array of integers 5 // length: the length of array numbers 6 // duplication: (Output) the duplicated number in the array number 7 // Return value: true if the input is valid, and there are some duplications in the array number 8 // otherwise false 9 bool duplicate(int numbers[], int length, int* duplication) 10 { 11 if(numbers==NULL||length<=0) 12 return false; 13 for(int i=0;i<length;++i) 14 { 15 if(numbers[i]<0||numbers[i]>length-1) 16 return false; 17 } 18 for(int i=0;i<length;++i) 19 { 20 while(numbers[i]!=i) 21 { 22 if(numbers[i]==numbers[numbers[i]]) 23 { 24 *duplication=numbers[i]; 25 return true; 26 } 27 int temp=numbers[i]; 28 numbers[i]=numbers[temp]; 29 numbers[temp]=temp; 30 } 31 } 32 return false; 33 } 34 };
3.构建乘积数组
给定一个数组A[0,1,...,n-1],请构建一个数组B[0,1,...,n-1],其中B中的元素B[i]=A[0]*A[1]*...*A[i-1]*A[i+1]*...*A[n-1]。不能使用除法。
分析:
B[i]的值可以看作下图的矩阵中每行的乘积。
下三角用连乘可以很容求得,上三角,从下向上也是连乘。
因此我们的思路就很清晰了,先算下三角中的连乘,即我们先算出B[i]中的一部分,然后倒过来按上三角中的分布规律,把另一部分也乘进去。
1 class Solution { 2 public: 3 vector<int> multiply(const vector<int>& A) 4 { 5 int n=A.size(); 6 vector<int> B(n); 7 B[0]=1; 8 for(int i=1;i<n;++i) 9 { 10 B[i]=B[i-1]*A[i-1]; 11 } 12 double temp=1; 13 for(int i=n-2;i>=0;--i) 14 { 15 temp*=A[i+1]; 16 B[i]*=temp; 17 } 18 return B; 19 } 20 };
4.表示数值的字符串
请实现一个函数用来判断字符串是否表示数值(包括整数和小数)。
例如,字符串"+100","5e2","-123","3.1416"和"-1E-16"都表示数值。 但是"12e","1a3.14","1.2.3","+-5"和"12e+4.3"都不是。
分析:在代码里体现
1 class Solution { 2 public: 3 bool isNumeric(char* string) 4 { 5 if(string==NULL) 6 return false; 7 if(*string=='+'||*string=='-')//首先判断第一个字符是不是正负号 8 ++string; 9 if(*string=='