Question

convert the following code from python to java.

def topkFrequent(nums, k): if not nums: return [ ] if len(nums) == 1: return nums [0] # first find freq freq dict d = {} for

0 0
Add a comment Improve this question Transcribed image text
Answer #1

// PLEASE LIKE THE SOLUTION
// FEEL FREE TO DISCUSS IN COMMENT SECTION
// Java Program

import java.util.*;

class Frequent{
   // function topKFrequent
   static int[] topKFrequent(int array[],int k){
       // defining array of 100000 length
       // for hashing

       int arr[] = new int[100000];
       int value[] = new int[100000];

       // all values are initialized with 0
       // now update frequency

       for(int i=0;i<arr.length;i++){
           arr[i] = 0;
           value[i] = i;
       }

       // now update frequency
       for(int i=0;i<array.length;i++){
           arr[array[i]]++;
       }

       // now sort
       for(int i=0;i<arr.length;i++){
           for(int j=i+1;j<arr.length;j++){
               if(arr[i] < arr[j]){
                   int temp = arr[i];
                   arr[i] = arr[j];
                   arr[j] = temp;

                   temp = value[i];
                   value[i] = value[j];
                   value[j] = temp;
               }
           }
       }

       int top[] = new int[k];

       // now adding to array top k frequent
       for(int i=0;i<k;i++){
           top[i] = value[i];
       }
       return top;
   }

   // main method
   public static void main(String arg[]){
       // input list
       Scanner scan = new Scanner(System.in);
       String inp = scan.nextLine();

       //String s = scan.next();

       // array split by space
       String values[] = inp.split(" ");

       // now parse to int
       int array[] = new int[values.length];

       for(int i=0;i<array.length;i++){
           array[i] = Integer.parseInt(values[i]);
       }

       // scan k
       int k = scan.nextInt();

       // call top k
       int result[] = topKFrequent(array,k);

       // printing the result
       for(int i=0;i<result.length;i++){
           System.out.println((i+1)+". "+result[i]);
       }
   }
}

// SAMPLE OUTPUT

kashyap@kashyap-Inspiron-3542:-/Pictures/cch$ javac Program.java kashyap@kashyap-Inspiron-3542:~/Pictures/cch$ java Frequent

Add a comment
Know the answer?
Add Answer to:
convert the following code from python to java. def topkFrequent(nums, k): if not nums: return [...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • python programming: Can you please add comments to describe in detail what the following code does:...

    python programming: Can you please add comments to describe in detail what the following code does: import os,sys,time sl = [] try:    f = open("shopping2.txt","r")    for line in f:        sl.append(line.strip())    f.close() except:    pass def mainScreen():    os.system('cls') # for linux 'clear'    print("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%")    print(" SHOPPING LIST ")    print("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%")    print("\n\nYour list contains",len(sl),"items.\n")    print("Please choose from the following options:\n")    print("(a)dd to the list")    print("(d)elete from the list")    print("(v)iew the...

  • Please, I need help debuuging my code. Sample output is below MINN = 1 MAXX =...

    Please, I need help debuuging my code. Sample output is below MINN = 1 MAXX = 100 #gets an integer def getValidInt(MINN, MAXX):     message = "Enter an integer between" + str(MINN) + "and" + str(MAXX)+ "(inclusive): "#message to ask the user     num = int(input(message))     while num < MINN or num > MAXX:         print("Invalid choice!")         num = int(input(message))     #return result     return num #counts dupes def twoInARow(numbers):     ans = "No duplicates next to each...

  • 11p Python Language Read the following code for oofraction. import oofraction class OOFraction: def main(): fl...

    11p Python Language Read the following code for oofraction. import oofraction class OOFraction: def main(): fl = oofraction.o0Fraction( 2, 5) f2 = oofraction.o0Fraction ( 1, 3) f3 = f1 + f2 print (str(3)) main() def __init__(self, Num, Den): self.mNum = Num self.mDen = Den return def_add_(self,other): num = self.mNumother.mDen + other.mNum*self.mDen den = self.mDen*other.mDen f = OOFraction(num,den) return f 1. Write the output below. def_str_(self): s = str( self.mNum )+"/" + str( self.mDen) returns 2. Write a class called wholeNum...

  • Python 12.10 LAB: Sorting TV Shows (dictionaries and lists) Write a program that first reads in...

    Python 12.10 LAB: Sorting TV Shows (dictionaries and lists) Write a program that first reads in the name of an input file and then reads the input file using the file.readlines() method. The input file contains an unsorted list of number of seasons followed by the corresponding TV show. Your program should put the contents of the input file into a dictionary where the number of seasons are the keys, and a list of TV shows are the values (since...

  • in python and according to this #Creating class for stack class My_Stack: def __init__(self): self.items = [] def isEmpty(self): return self.items == [] def Push(self, d): self.items.append(d) def Po...

    in python and according to this #Creating class for stack class My_Stack: def __init__(self): self.items = [] def isEmpty(self): return self.items == [] def Push(self, d): self.items.append(d) def Pop(self): return self.items.pop() def Display(self): for i in reversed(self.items): print(i,end="") print() s = My_Stack() #taking input from user str = input('Enter your string for palindrome checking: ') n= len(str) #Pushing half of the string into stack for i in range(int(n/2)): s.Push(str[i]) print("S",end="") s.Display() s.Display() #for the next half checking the upcoming string...

  • def average_word_length(string): num_words = 0 if not type(string)==str: return "Not a string" if not "A" or...

    def average_word_length(string): num_words = 0 if not type(string)==str: return "Not a string" if not "A" or not "B" or not "C" or not "D" or not "E" or not "F" or not "G" or not "H" or not "I" or not "J"\ or not "K" or not "L" or not "M" or not "N" or not "O" or not "P" or not "Q" or not "R" or not "S" or not "T"\ or not "U" or not "V" or not...

  • Write a python program write a function numDigits(num) which counts the digits in int num. Answer...

    Write a python program write a function numDigits(num) which counts the digits in int num. Answer code is given in the Answer tab (and starting code), which converts num to a str, then uses the len() function to count and return the number of digits. Note that this does NOT work correctly for num < 0. (Try it and see.) Fix this in two different ways, by creating new functions numDigits2(num) and numDigits3(num) that each return the correct number of...

  • Python Problem Hello i am trying to finish this code it does not save guesses or...

    Python Problem Hello i am trying to finish this code it does not save guesses or count wrong guesses. When printing hman it needs to only show _ and letters together. For example if the word is amazing and guess=a it must print a_a_ _ _ _ not a_ _ _ _ and _a_ _ _ separately or with spaces. The guess has a maximum of 8 wrong guesses so for every wrong guess the game must count it if...

  • Page 3 of 7 (Python) For each substring in the input string t that matches the...

    Page 3 of 7 (Python) For each substring in the input string t that matches the regular expression r, the method call re. aub (r, o, t) substitutes the matching substring with the string a. Wwhat is the output? import re print (re.aub (r"l+\d+ " , "$, "be+345jk3726-45+9xyz")) a. "be$jk3726-455xyz" c. "bejkxyz" 9. b. "be$jks-$$xyz" d. $$$" A object a- A (2) 10. (Python) What is the output? # Source code file: A.py class A init (self, the x): self.x-...

  • Explain what the code is doing line from line explanations please or summarize lines with an explanation def displayCart(): #displays the cart function """displayCart function - dis...

    Explain what the code is doing line from line explanations please or summarize lines with an explanation def displayCart(): #displays the cart function """displayCart function - displays the items in the cart ---------------------------------------------------------------------""" import os os.system('clear') print("\n\nCart Contents:") print("Your selected items:", cart) def catMenu(): #function that displays the category menu """catMenu function - displays the categories user picks from ---------------------------------------------------------------------""" import os os.system('clear') print(""" 1 - Books 2 - Electronics 3 - Clothing d - display cart contents x -...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT