标签 hot100 下的文章

题目链接:最大子数组和

给你一个整数数组 nums ,请你找出一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。

方法:动态规划

class Solution {
public:
    int maxSubArray(vector<int>& nums) {
        int ans = nums[0];
        int t = 0;
        for (int num:nums) {
            t = max(num,t+num);
            ans = max(ans,t);
        }
        return ans;
    }
};

题目链接:盛最多水的容器

给定一个长度为 n 的整数数组 height 。有 n 条垂线,第 i 条线的两个端点是 (i, 0) 和 (i, height[i]) 。

找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。

返回容器可以储存的最大水量。

方法:双指针

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

题目链接:移动零

给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。

请注意 ,必须在不复制数组的情况下原地对数组进行操作。

方法:哈希表

class Solution {
public:
    void moveZeroes(vector<int>& nums) {
        int n = nums.size(),l = 0,r = 0;
        while (r < n) {
            if (nums[r]) {
                swap(nums[l],nums[r]);
                l++;
            }
            r++;
        }
    }
};

题目链接:最长连续序列

给定一个未排序的整数数组 nums ,找出数字连续的最长序列(不要求序列元素在原数组中连续)的长度。

请你设计并实现时间复杂度为 O(n) 的算法解决此问题。

方法:哈希表

class Solution {
public:
    int longestConsecutive(vector<int>& nums) {
        unordered_set<int> nums_set;
        for (int num : nums) {
            nums_set.insert(num);
        }
        int ans = 0;
        for (int num : nums_set) {
            if (!nums_set.count(num-1)) {
                int cur = num;
                int curs = 1;
                while (nums_set.count(cur+1)) {
                    cur += 1;
                    curs += 1;
                }
                ans = max(ans,curs);
            }
        }
        return ans;
    }
};

题目链接:字母异位词分组

给你一个字符串数组,请你将 字母异位词 组合在一起。可以按任意顺序返回结果列表。

方法:排序

class Solution {
public:
    vector<vector<string>> groupAnagrams(vector<string>& strs) {
        vector<vector<string>> ans;
        unordered_map<string,vector<string>> mp;
        for (string& str : strs) {
            string key = str;
            sort(key.begin(),key.end());
            mp[key].emplace_back(str);
        }
        for (auto it = mp.begin();it != mp.end();it++) {
            ans.emplace_back(it->second);
        }
        return ans;
    }
};