You are given a 2D matrix
of size m x n
, consisting of non-negative integers. You are also given an integer k
.
The value of coordinate (a, b)
of the matrix is the XOR of all matrix[i][j]
where 0 <= i <= a < m
and 0 <= j <= b < n
(0-indexed).
Find the kth
largest value (1-indexed) of all the coordinates of matrix
.
Example 1:
Input: matrix = [[5,2],[1,6]], k = 1 Output: 7 Explanation: The value of coordinate (0,1) is 5 XOR 2 = 7, which is the largest value.
Example 2:
Input: matrix = [[5,2],[1,6]], k = 2 Output: 5 Explanation: The value of coordinate (0,0) is 5 = 5, which is the 2nd largest value.
Example 3:
Input: matrix = [[5,2],[1,6]], k = 3 Output: 4 Explanation: The value of coordinate (1,0) is 5 XOR 1 = 4, which is the 3rd largest value.
Example 4:
Input: matrix = [[5,2],[1,6]], k = 4 Output: 0 Explanation: The value of coordinate (1,1) is 5 XOR 2 XOR 1 XOR 6 = 0, which is the 4th largest value.
Constraints:
m == matrix.length
n == matrix[i].length
1 <= m, n <= 1000
0 <= matrix[i][j] <= 106
1 <= k <= m * n
Solution: DP
Similar to 花花酱 LeetCode 304. Range Sum Query 2D – Immutable
xor[i][j] = matrix[i][j] ^ xor[i – 1][j – 1] ^ xor[i – 1][j] ^ xor[i][j- 1]
Time complexity: O(mn)
Space complexity: O(mn)
C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
// Author: Huahua class Solution { public: int kthLargestValue(vector<vector<int>>& matrix, int k) { const int m = matrix.size(), n = matrix[0].size(); vector<int> v; for (int i = 0; i < m; ++i) for (int j = 0; j < n; ++j) v.push_back(matrix[i][j] ^= (i ? matrix[i - 1][j] : 0) ^ (j ? matrix[i][j - 1] : 0) ^ (i * j ? matrix[i - 1][j - 1] : 0)); nth_element(begin(v), begin(v) + k - 1, end(v), greater<int>()); return v[k - 1]; } }; |
请尊重作者的劳动成果,转载请注明出处!花花保留对文章/视频的所有权利。
如果您喜欢这篇文章/视频,欢迎您捐赠花花。
If you like my articles / videos, donations are welcome.
Be First to Comment