【问题标题】:Error with List.removeIf - Kth Largest Element in an ArrayList.removeIf 出错 - 数组中的第 K 个最大元素
【发布时间】:2022-01-24 05:04:01
【问题描述】:

我正在尝试查找数组中第 K 个最大的元素。

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

class Solution {
    public int findKthLargest(int[] nums, int k) {
        //List<Integer> list = Arrays.asList(nums); 
        List<Integer> list = IntStream.of(nums).boxed().collect(Collectors.toList());
        int max = nums[0];

        for(int x = 1; x<=k; x++){
            for(int y = 1; y<list.size(); y++){
                int temp;
                if (nums[y] > max) {
                    max = nums[y];
                    temp = max;
                }
            }
        list.removeIf(value -> value.equals(temp.valueOf()));
        }
    return max;
    }
}

我遇到了错误:

第 20 行:错误:找不到符号 list.removeIf(value -> value.equals(temp.valueOf())); ^ 符号:可变温度 位置:类解决方案

如果我在两个 for 循环语句之间移动 int temp,我会收到此错误。

第 21 行:错误:无法取消引用 int list.removeIf(value -> value.equals(temp.valueOf())); ^

【问题讨论】:

  • List.removeIf 自 Java 8 起可用。您使用的是什么 Java 版本?

标签: java arrays performance arraylist


【解决方案1】:

如果任务只是找到第 K 个最大元素,则不应从列表/数组中删除任何内容。

只需对数组进行排序并返回从末尾开始计数的第 k 个值:

public static int findKthLargest(int[] nums, int k) {
    assert(k > 0 && k < nums.length); // make sure k is valid
    Arrays.sort(nums);
    return nums[nums.length - k];
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-10-06
    • 1970-01-01
    • 2019-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-21
    相关资源
    最近更新 更多