双指针(搬运)

class Solution {

    bool isMatch(const string& s, const string& t) {
        int i = 0;
        int j = 0;
        while(i < s.size() && j < t.size()) {
            if(s[i] == t[j]) {
                ++i, ++j;
            }else {
                ++i;
            }
        }
        return j == t.size();
    }

public:
    string findLongestWord(string s, vector<string>& dictionary) {
        sort(dictionary.begin(), dictionary.end(), [&](const auto& a, const auto& b) {
            if(a.size() == b.size()) {
                return a < b;
            }
            return a.size() > b.size();
        });                                             // (1)
        for(int i = 0; i < dictionary.size(); ++i) {
            if( isMatch(s, dictionary[i]) ) {
                return dictionary[i];
            }
        }

        return "";
    }
};

int cmp(const void*a, const void*b) {
    return *(int *)a - *(int *)b;
}

int maxOperations(int* nums, int numsSize, int k) {
    int l = 0;
    int ans = 0;
    int r = numsSize - 1;
    qsort(nums, numsSize, sizeof(int), cmp);
    while(l < r) {
        int val = nums[l] + nums[r];
        if(val > k) {
            --r;
        }else if(val < k) {
            ++l;
        }else {
            ++l, --r;
            ++ans;
        }
    }
    return ans;
}

struct ListNode *detectCycle(struct ListNode *head) {
    struct ListNode *fast = head, *slow = head;
    if(fast == NULL) {
        return NULL;
    }
    while(1) {                   // (1)
        slow = slow->next;
        fast = fast->next;
        if(fast == NULL) {
            return NULL;
        }
        fast = fast->next;
        if(fast == NULL) {
            return NULL;
        }
        if(fast == slow) break;
    }
    fast = head;                 // (2)
    while(fast != slow) {        // (3)
        fast = fast->next;
        slow = slow->next;
    }
    return fast;
    
}

posted @ 2022-06-06 00:08  越菜越自信  阅读(25)  评论(0)    收藏  举报