LeetCode刷题日记(Day9)

Problem 49. Group Anagrams

  • 题目描述
    Given an array of strings, group anagrams together.

    Example:

    Input: ["eat", "tea", "tan", "ate", "nat", "bat"],
    Output:
    [
      ["ate","eat","tea"],
      ["nat","tan"],
      ["bat"]
    ]
    
  • 解题思路
    本题是要将输入的字符串分成若干组,每组的字符串之间拥有相同的字符。

    一个可行的办法是对传入的字符串内部进行排序,例如将"ate",“eat”,“tea"都处理成"aet”。定义 map<string, vector< string> >变量 m,将处理后相同的字符串映射到同一个 vector< string>中。

  • 代码实现

class Solution {
public:
    vector<vector<string> > groupAnagrams(vector<string>& strs) {
        vector<vector<string> > res;
        if(strs.empty())
            return res;
        map<string, vector<string> > m;
        for(int i = 0; i < strs.size(); ++i){
            string s = strs[i];
            sort(s.begin(), s.end());
            m[s].push_back(strs[i]);
        }
        map<string, vector<string> >::iterator i;
        for(i = m.begin(); i != m.end(); ++i)
            res.push_back(i->second);       
        return res;
    }
};

Problem 50. Pow(x, n)

  • 题目描述
    Implement pow(x, n), which calculates x raised to the power n.

  • 解题思路
    本题要实现的是一个求乘方的函数 double myPow(double x, int n),例如 myPow(3, 4) = 3^4 = 81。

    若直接对传入的x累乘n次,时间复杂度为O(n),在本题中会超时。

    下面给出一种 O(log n) 的算法,该算法原理如下:

    1. 定义一个 double 变量 res,初始化为1.0,用于储存返回的结果。
    2. 对 n 进行折半处理,如果n为偶数,则令x *= x(假设x是3,n 是4。进行一次折半处理后n变成2,x 变成3 *3=9;再进行一次折半处理后 n 变成1,x 变成9 *9=81,这就是答案。)
    3. 如果n是奇数,则在令x *= x的同时,也要令res = res * x。(当 n=5 和 n=4 时,对 n 进行折半后都变成了2,显然 n=5时要进行多一次的乘法操作。所以,当 n 为奇数时,会造成幂操作的损失,所以使用 res = res * x 将损失的幂操作补足)。
    4. 将得到的 x 与 res 相乘,并返回结果。
  • 代码实现

class Solution {
public:
    double myPow(double x, int n) {
        double res = 1.0;
        for(int i = n; i != 0; i /= 2){
            if(i % 2 != 0)
                res *= x;
            x *= x;
        }
        if(n < 0)
            res = 1/res;
        return res;
    }
};

Problem 53. Maximum Subarray

  • 题目描述
    Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.

    Example:

    Input: [-2,1,-3,4,-1,2,1,-5,4],
    Output: 6
    Explanation: [4,-1,2,1] has the largest sum = 6.
    
  • 解题思路
    设传入的数组为 nums,定义 int 变量 res 和 cur,并初始化为 nums[0]。其中 cur 表示当前子数组的和,res 表示所有子数组的和的最大值。
    对 nums 进行遍历,每次更新 cur 和 res 的值,更新规则如下:

  1. 若 cur + nums[i] > nums[i],则 cu r赋值为 cur + nums[i],否则赋值为 nums[i](即如果 cur 是负数,那么 nums[i] 加上之前的子数组的和只会更小,还不如计算从 nums[i] 开始的新的子数组的和)。
  2. 取 cur 和 res 中的最大值,并赋值给 res(即统计出和最大的子数组)。
  • 代码实现
class Solution {
public:
    int maxSubArray(vector<int>& nums) {
        int res = nums[0];
        int cur = nums[0];
        for(int i = 1; i < nums.size(); ++i){
            cur = (cur + nums[i] > nums[i]) ? cur + nums[i] : nums[i];
            res = (cur > res) ? cur : res;
        }
        return res;
    }
};

Problem 54. Spiral Matrix

  • 题目描述
    Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.

    Example:

    Input:
    [
     [ 1, 2, 3 ],
     [ 4, 5, 6 ],
     [ 7, 8, 9 ]
    ]
    Output: [1,2,3,6,9,8,7,4,5]
    
  • 解题思路
    令 top、bottom、left、right 分别表示矩阵的首行、末行、首列、末列,并进行相应的初始化。在满足 top <= bottom 且 left <= right 的条件下,不断地对矩阵进行右,下,左,上遍历即可得到答案。

  • 代码实现

class Solution {
public:
    vector<int> spiralOrder(vector<vector<int> >& matrix) {
        vector<int> res;
        int row = matrix.size();
        if(row == 0)
            return res;
        int col = matrix[0].size();
        if(col == 0)
            return res;
        int top = 0, bottom = row-1, left = 0, right = col-1;
        while(top <= bottom && left <= right){
            for(int i = left; i <= right; ++i)
                res.push_back(matrix[top][i]);
            if(++top > bottom) 
                break;
            
            for(int i = top; i <= bottom; ++i)
                res.push_back(matrix[i][right]);
            if(--right < left)
                break;

            for(int i = right; i >= left; --i)
                res.push_back(matrix[bottom][i]);
            if(--bottom < top)
                break;

            for(int i = bottom; i >= top; --i)
                res.push_back(matrix[i][left]);
            if(++left > right)
                break;
        }
        return res;
    }
};

Problem 55. Jump Game

  • 题目描述
    Given an array of non-negative integers, you are initially positioned at the first index of the array.

    Each element in the array represents your maximum jump length at that position.

    Determine if you are able to reach the last index.

    Example:

    Input: [2,3,1,1,4]
    Output: true
    Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index.
    
  • 解题思路
    判断能否跳到终点,只要在遍历数组 nums 的时候,更新每个点所能达到的最远范围 farthest 即可。如果最后 farthest 不比最后一个点短,则表示能到到达终点。

  • 代码实现

class Solution {
public:
    bool canJump(vector<int>& nums) {
        int farthest = 0;
        for(int i = 0; i < nums.size(); ++i){
            if(i > farthest)
                return false;
            farthest = max(farthest, nums[i]+i);
        }
        return true;
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_36348299/article/details/88574945
今日推荐