CPP-回文数-KMP-爬楼梯-最大子段和-牛顿迭代法开方-二分查找法
回文数
通过比较后段的数与前段的数的大小关系实现
class Solution {
public:
bool isPalindrome(int x) {
if(x<0 || (x>0 && x%10 == 0)){
return false;
}
int sum = 0;
while (x > sum)
{
sum = sum*10 + x%10;
x/=10;
}
return x==sum || x==sum/10;
}
};
KMP
class Solution {
public:
vector<int> getnext(string needle){
vector<int> next(needle.size(),0);
next[0] = -1;
int j=0,k=-1;
while(j<needle.size()-1){
if(k==-1||needle[j]==needle[k]){
next[++j]=++k;
}
else{
k=next[k];
}
}
return next;
}
//kmp
int strStr(string haystack, string needle) {
vector<int> next =getnext(needle);
int i=0,j=0,hs=haystack.size(),ns=needle.size();
while(i<haystack.length()&&j<(int)needle.length()){
if(j==-1||haystack[i]==needle[j]){
i++;
j++;
}
else{
j = next[j];
}
}
if(j==needle.size())return i-j;
return -1;
}
};
爬楼梯
经典动态规划
即只能一次爬1或2级台阶,求n级台阶时有几种组合方法
class Solution {
public:
int climbStairs(int n) {
//正常的动态规划
// vector<int> dp(n+1);
// // dp[0]=0;
// // dp[1]=1;
// // dp[2]=2;
// for(int i=0;i<n+1;i++){
// if(i<3) dp[i]=i;
// else dp[i] = dp[i-1] + dp[i-2];
// cout<<dp[i]<<',';
// }
//打表
int dp[] = {0,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,1597,2584,4181,6765,10946,17711,28657,46368,75025,121393,196418,317811,514229,832040,1346269,2178309,3524578,5702887,9227465,14930352,24157817,39088169,63245986,102334155,165580141,267914296,433494437,701408733,1134903170,1836311903};
return dp[n];
}
};
最大子段和
经典动态规划
class Solution {
public:
int maxSubArray(vector<int>& nums) {
int res=INT_MIN,t=0;
for(int i=0;i<nums.size();i++){
t+=nums[i];
if(t>res)res=t;
if(t<0)t=0;
}
return res;
}
};
牛顿迭代法开方
class Solution {
public:
int mySqrt(int x) {
long x1 = x;
if(!x1)return 0;
while(x1*x1 > x){
x1 = (x1 + x/x1 )/2;
}
return x1;
}
};
二分法寻找插入值位置
class Solution {
public:
int searchInsert(vector<int>& nums, int target) {
int res1,lef = 0,rig=nums.size()-1;
while(lef<=rig){
res1 = (rig+lef)/2;
if(nums[res1] == target)return res1;
else if(nums[res1]>target) rig = res1-1;
else lef = res1+1;
}
return lef;
}
};
本文来自博客园,作者:ghosteq,转载请注明原文链接:https://www.cnblogs.com/ghosteq/articles/16187777.html

浙公网安备 33010602011771号