LeetCode实战练习题目 - Array

Posted insist钢

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode实战练习题目 - Array相关的知识,希望对你有一定的参考价值。

实战练习题目 - Array

盛最多水的容器

class Solution {
public:
int maxArea(vector<int>& height) {
    int res = 0;
    int i = 0;
    int j = height.size() - 1;
    while (i < j) {
        int area = (j - i) * min(height[i], height[j]);
        res = max(res, area);
        if (height[i] < height[j]) {
            i++;
        } else {
            j--;
        }
    }
    return res;
}
};

移动零

class Solution {
public:
    void moveZeroes(vector<int>& nums) {
        int n = nums.size();

        int numZeroes = 0;
        for (int i = 0; i < n; i++) {
            numZeroes += (nums[i] == 0);
        }
        vector<int> ans;
        for (int i = 0; i < n; i++) {
            if (nums[i] != 0) {
                ans.push_back(nums[i]);
            }
        }

        while (numZeroes--) {
            ans.push_back(0);
        }
        for (int i = 0; i < n; i++) {
            nums[i] = ans[i];
        }
    
    }
};

爬楼梯

class Solution {
public:
    long long GetCni(int n, int i) {
        i = (n - i > i)? i : (n - i);
        if(i == 0) return 1;
        else return GetCni(n, i-1)*(n-i+1)/i;
    }
    int climbStairs(int n) {
        int i = 0;
        int Sum = 0;
        while(i <= n/2) {
            Sum += GetCni(n-i, i);
            i++;
        }
        return Sum;
    }
};

三数之和

class Solution {
public:
    vector<vector<int> > threeSum(vector<int>& nums) {
        vector<vector<int> > ret;
        vector<int > vtemp;
        int len = nums.size();
        sort(nums.begin(),nums.end());//sort the input
        for(int i=0;i<len-2;i++){
            if(i ==0 ||(i>0 && nums[i] != nums[i-1])){
                int p1 = i+1, p2 = len-1; // set two pointers
                while(p1 < p2){
                    if(nums[p1] + nums[p2] < -nums[i]){
                        p1++;
                    }else if(nums[p1] + nums[p2] == -nums[i]){
                        if(p1 == i+1){
                            vector<int > vtemp{nums[i], nums[p1], nums[p2]};
                            ret.push_back(vtemp);
                            vtemp.clear();

                        }else if(nums[p1] != nums[p1-1]){
                            vector<int > vtemp{nums[i], nums[p1], nums[p2]};
                            ret.push_back(vtemp);
                            vtemp.clear();

                        }
                        p1++,p2--;
                    }else{
                         p2--;
                    }
                }
            }


        }
        return ret;

    }
};

以上是关于LeetCode实战练习题目 - Array的主要内容,如果未能解决你的问题,请参考以下文章

C 实战练习题目6

C 实战练习题目58

C 实战练习题目62

C 实战练习题目57

C 实战练习题目63

C 实战练习题目51