class Solution {
public:
int removeElement(vector<int>& nums, int val) {
int len=nums.size();
int p=0;
int q=0;
while(q<len){
if(nums[q]!=val){
nums[p]=nums[q];
p++;
}
q++;
}
return p;
}
};
二.通用解法
class Solution {
public:
int removeElement(vector<int>& nums, int val) {
int idx = 0;
for(auto x : nums)
if(x != val)nums[idx++] = x;
return idx;
}
};
28.找出字符串中第一个匹配项的下标
一.朴素解法 c++
class Solution {
public:
int strStr(string haystack, string needle) {
int p=haystack.size();
int q=needle.size();
int n=0;
for(int i=0;i<=p-q;i++){
int j=i;
while(n<q&&haystack[j]==needle[n]){
j++;
n++;
}
if(n==q) return i;
}
return -1;}
};
二.API秒
class Solution {
public int strStr(String haystack, String needle) {
return haystack.indexOf(needle);
}
}
三.KMP解法
class Solution {
public:
int strStr(string s, string p) {
int n = s.size(), m = p.size();
if(m == 0) return 0;
//设置哨兵
s.insert(s.begin(),' ');
p.insert(p.begin(),' ');
vector<int> next(m + 1);
//预处理next数组
for(int i = 2, j = 0; i <= m; i++){
while(j and p[i] != p[j + 1]) j = next[j];
if(p[i] == p[j + 1]) j++;
next[i] = j;
}
//匹配过程
for(int i = 1, j = 0; i <= n; i++){
while(j and s[i] != p[j + 1]) j = next[j];
if(s[i] == p[j + 1]) j++;
if(j == m) return i - m;
}
return -1;
}
};
class Solution {
public:
int strStr(string ss, string pp) {
if (pp.size()<=0)
return 0;
//int sum=0; 求子串出现次数
// 分别读取原串和匹配串的长度
int n = ss.length(), m = pp.length();
// 原串和匹配串前面都加空格,使其下标从 1 开始
ss = " " + ss;
pp = " " + pp;
string s=ss;
string p=pp;
// 构建 next 数组,数组长度为匹配串的长度(next 数组是和匹配串相关的)
int next[m + 1];
memset(next,0,sizeof(next));
// 构造过程 i = 2,j = 0 开始,i 小于等于匹配串长度 【构造 i 从 2 开始】
for (int i = 2, j = 0; i <= m; i++) {
// 匹配不成功的话,j = next(j)
while (j > 0 && p[i] != p[j + 1])
j = next[j];
// 匹配成功的话,j++
if (p[i] == p[j + 1])
j++;
next[i] = j;
}
// 匹配过程,i = 1,j = 0 开始,i 小于等于原串长度 【匹配 i 从 1 开始】
for (int i = 1, j = 0; i <= n; i++) {
// 匹配不成功 j = next(j)
while (j > 0 && s[i] != p[j + 1])
j = next[j];
// 匹配成功 j++
if (s[i] == p[j + 1]) j++;
// 如果匹配成功了,直接返回
if (j == m) {
return i-m;
//sum++;求子串出现次数就用这个
}
}
//return sum;
return -1;
}
};
35.搜索插入位置
二分查找
class Solution {
public:
int searchInsert(vector<int>& nums, int target) {
int len=nums.size();
if(nums[len-1]<target){
return len;}
int left=0;
int right=len-1;
while(left<right){
int mid=((left+right)/2);
if(nums[mid]<target){
left=mid+1;
}else{
right=mid;
}
}
return left;
}
};