Loading

【LBLD】双指针技巧秒杀七道数组题目

【LBLD】双指针技巧秒杀七道数组题目

快慢指针技巧

class Solution {
public:
    int removeDuplicates(vector<int>& nums) {
        int fast = 0;
        int slow = 0;
        while (fast < nums.size()) {
            if (nums.at(fast) != nums.at(slow)) {
                nums.at(++slow) = nums.at(fast);
            }
            fast++;
        }
        return slow+1;
    }
};

左右指针的常用算法

2、两数之和

class Solution {
public:
    vector<int> twoSum(vector<int>& numbers, int target) {
        int left = 0, right = numbers.size()-1;
        int sum = numbers[left] + numbers[right];
        while (left < right) {
            if (sum == target) {
                return {left+1, right+1};
            }
            else if (sum < target) {
                left++;
            }
            else {
                right--;
            }
            sum = numbers[left] + numbers[right];
        }
        return {-1, -1};
    }
};

3、反转数组

class Solution {
public:
    void reverseString(vector<char>& s) {
        int left = 0, right = s.size()-1;
        char temp = '\0';
        while (left < right) {
            temp = s[left];
            s[left] = s[right];
            s[right] = temp;
            left++; right--;
        }
    }
};

4、回文串判断

class Solution {
public:
    string palindromeLength(string s, int i, int j) {
        int left = i, right = j;
        while (left >= 0 && right < s.size() && s[left] == s[right]) {
            left--; right++;
        }
        return s.substr(left+1, right-left-1);
    }

    string longestPalindrome(string s) {
        string ans = "";
        string res1 = "", res2 = "";
        for (int i = 0; i < s.size(); i++) {
            res1 = palindromeLength(s, i, i);
            res2 = palindromeLength(s, i, i+1);
            ans = ans.size() > res1.size() ? ans : res1;
            ans = ans.size() > res2.size() ? ans : res2;
        }
        return ans;
    }
};
posted @ 2023-03-31 11:00  杨谖之  阅读(14)  评论(0编辑  收藏  举报