leetcode 1738. 找出第 K 大的异或坐标值
Posted 深林无鹿
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode 1738. 找出第 K 大的异或坐标值相关的知识,希望对你有一定的参考价值。
这里有leetcode题集分类整理!!!
题目难度: 中等
题目描述:
前缀和 + 集合排序
class Solution
public int kthLargestValue(int[][] matrix, int k)
int n = matrix.length;
int m = matrix[0].length;
int[][] prefix = new int[n + 1][m + 1];
List<Integer> results = new ArrayList<>();
for (int i = 1; i <= n; i ++)
for (int j = 1; j <= m; j ++)
prefix[i][j] = prefix[i - 1][j] ^ prefix[i][j - 1] ^ prefix[i - 1][j - 1] ^ matrix[i - 1][j - 1];
results.add(prefix[i][j]);
Collections.sort(results, new Comparator<Integer>()
public int compare(Integer num1, Integer num2)
return num2 - num1;
);
return results.get(k - 1);
官解: 前缀和 + 快速选择排序
class Solution
public int kthLargestValue(int[][] matrix, int k)
int m = matrix.length, n = matrix[0].length;
int[][] pre = new int[m + 1][n + 1];
List<Integer> results = new ArrayList<Integer>();
for (int i = 1; i <= m; ++i)
for (int j = 1; j <= n; ++j)
pre[i][j] = pre[i - 1][j] ^ pre[i][j - 1] ^ pre[i - 1][j - 1] ^ matrix[i - 1][j - 1];
results.add(pre[i][j]);
nthElement(results, 0, k - 1, results.size() - 1);
return results.get(k - 1);
public void nthElement(List<Integer> results, int left, int kth, int right)
if (left == right)
return;
int pivot = (int) (left + Math.random() * (right - left + 1));
swap(results, pivot, right);
// 三路划分(three-way partition)
int sepl = left - 1, sepr = left - 1;
for (int i = left; i <= right; i++)
if (results.get(i) > results.get(right))
swap(results, ++sepr, i);
swap(results, ++sepl, sepr);
else if (results.get(i) == results.get(right))
swap(results, ++sepr, i);
if (sepl < left + kth && left + kth <= sepr)
return;
else if (left + kth <= sepl)
nthElement(results, left, kth, sepl);
else
nthElement(results, sepr + 1, kth - (sepr - left + 1), right);
public void swap(List<Integer> results, int index1, int index2)
int temp = results.get(index1);
results.set(index1, results.get(index2));
results.set(index2, temp);
作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/find-kth-largest-xor-coordinate-value/solution/zhao-chu-di-k-da-de-yi-huo-zuo-biao-zhi-mgick/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
以上是关于leetcode 1738. 找出第 K 大的异或坐标值的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode 1738. 找出第 K 大的异或坐标值(Java动态规划)
LeetCode 1738. 找出第 K 大的异或坐标值(Java动态规划)