[力扣] 算法 1310 (C++)

1310. 子数组异或查询

class Solution {
public:
    vector<int> xorQueries(vector<int>& arr, vector<vector<int>>& queries) {
        for (size_t i = 1, size = arr.size(); i < size; ++i) {
            arr[i] ^= arr[i - 1];
        }
        vector<int> ret(queries.size());
        for (size_t i = 0, size = queries.size(); i < size; ++i) {
            int from = queries[i][0], to = queries[i][1];
            ret[i] = arr[to] ^ (from ? arr[from - 1] : 0);
        }
        return ret;
    }
};

[力扣] 算法 64 (C++)

64. 最小路径和

class Solution {
public:
    int minPathSum(vector<vector<int>>& grid) {
        const int m = grid.size();
        const int n = grid[0].size();
        for (int i = m - 2; i >= 0; --i)
            grid[i][n - 1] += grid[i + 1][n - 1];
        for (int i = n - 2; i >= 0; --i)
            grid[m - 1][i] += grid[m - 1][i + 1];
        for (int i = m - 2; i >= 0; --i)
            for (int j = n - 2; j >= 0; --j)
                 grid[i][j] += min(grid[i + 1][j], grid[i][j + 1]);
        return grid[0][0];
    }
};

[力扣] 算法 74 (C++)

74. 搜索二维矩阵

class Solution {
public:
    bool searchMatrix(vector<vector<int>>& matrix, int target) {
        int row = matrix.size();
        int col = matrix[0].size();
        int left = 0, right = row * col - 1;
        while (left < right) {
            auto mid = (left + right) / 2;
            auto num = matrix[mid / col][mid % col];
            if (num == target) 
                return true;
            if (num < target)
                left = mid + 1;
            else
                right = mid - 1;
        }
        return matrix[left / col][left % col] == target;
    }
};

[力扣] 算法 190 (C++)

190. 颠倒二进制位

class Solution {
public:
    uint32_t reverseBits(uint32_t n) {
        auto ret = (n >> 16) | (n << 16);// ((ret & 0xffff0000) >> 16) | ((ret & 0x0000ffff) << 16)
        ret = ((ret & 0xff00ff00) >> 8) | ((ret & 0x00ff00ff) << 8);
        ret = ((ret & 0xf0f0f0f0) >> 4) | ((ret & 0x0f0f0f0f) << 4);// 1111 0000
        ret = ((ret & 0xcccccccc) >> 2) | ((ret & 0x33333333) << 2);// 1100 0011
        ret = ((ret & 0xaaaaaaaa) >> 1) | ((ret & 0x55555555) << 1);// 1010 0101
        return ret;
    }
};