Leetcode 27~28_leetcode

Source: Internet
Author: User
Tags array length
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; }
};

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.