Leetcode 27. Remove Element Topic:
https://leetcode.com/problems/remove-element/description/:
Given an array and a value, the specified value is removed from the array and the new array length is returned after the removal.
Instead of allocating extra space for other arrays, you must modify the input array using the extra memory of O (1).
The order of the elements can be changed. Data other than the length of the new array returned is no matter what it is. Ideas:
Iterate over the array, not the given value, and put back the array code:
Class Solution {public
:
int removeelement (vector<int>& nums, int val) {
int index = 0;
for (int i = 0; i < nums.size (); ++i)
if (Nums[i]!= val)
nums[index++] = nums[i];
return index;
}
;
Leetcode 28. Implement STRSTR () topic:
https://leetcode.com/problems/implement-strstr/description/:
Implement Strstr ().
Returns the index of the first character of the needle contained in haystack, which returns 1 if needle is not part of the haystack. Ideas:
Straight out a KMP k m p algorithm code:
class Solution {public:int strstr (String haystack, string needle) {if (needle.size () = 0) return 0;
Vector<int> Next (Needle.size () +1);
int ans = KMP (haystack, needle, Next);
return ans;
} private:void GetNext (string &pat, vector<int> &next) {int i = 0, j =-1;
Next[0] =-1;
while (I < pat.size ()) {if (j = = 1 | | pat[i] = = Pat[j]) next[++i] = ++j;
else J = Next[j];
an int kmp (string &ori, String &pat, vector<int> &next) {GetNext (Pat, Next);
int i = 0, j = 0;
while (I < ori.size ()) {if (j = = 1 | | ori[i] = = Pat[j]) ++i, ++j;
else J = Next[j];
if (j = = Pat.size ()) return i-j;
} return-1; }
};