Can anyone help me find what is the problem of my Java code?


  • 1

    public class Solution {
    public List<Integer> topKFrequent(int[] nums, int k) {
    List<Integer> result = new ArrayList<>();
    Map<Integer, Integer>myMap = new HashMap<Integer, Integer>();
    int []mark = new int[nums.length];
    for (int i:nums){
    if(!myMap.containsKey(i)){
    myMap.put(i,1);
    }
    else{
    myMap.put(i,myMap.get(i)+1);
    }
    if(myMap.get(i) >= k && mark[i] == 0){
    result.add(i);
    mark[i] = 1;
    }
    }

    return result;
    }
    

    }
    The Submission Result is Runtime Error . I think I am really close to correct answer. The problem may occur on line 13.
    Thank you guys.


  • 0

    Two things here:

    • your code is really a mess here, you're gonna format your code properly using ``` next time before posting your question
    • your thoughts or your understanding of the problem is totally out of the track here, if you are not sure try the following test case with your solution.
    [1,1,1,2,2,3]
    1
    

    The problem is trying to find out the top k frequent here not just the frequency of one number. Read it again...if you truly cannot get it, directly contact me. Good luck.


  • -1
    K
    This post is deleted!

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.