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
  • convert this python code to c++ code def sort(a,b): if a > b: return b,a else:...

    convert this python code to c++ code def sort(a,b): if a > b: return b,a else: return a,b def main(): set1 = input('Enter the first pair of integers: ') set2 = input('Enter the second pair of integers: ') set3 = input('Enter the third pair of integers: ') set1 = set1.split(',') set1_0 = int(set1[0]) set1_1 = int(set1[1]) set2 = set2.split(',') set2_0 = int(set2[0]) set2_1 = int(set2[1]) set3 = set3.split(',') set3_0 = int(set3[0]) set3_1 = int(set3[1])    print(sort(set1_0,set1_1)) print(sort(set2_0,set2_1)) print(sort(set3_0,set3_1))

  • 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...

  • 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...

  • 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...

  • 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. Continues off another code(other code is below). I don't understand this. Someone please help! Comment...

    PYTHON. Continues off another code(other code is below). I don't understand this. Someone please help! Comment the lines please so I can understand. There are short and med files lengths for each the list of names/ids and then search id file. These are the input files: https://codeshare.io/aVQd46 https://codeshare.io/5M3XnR https://codeshare.io/2W684E https://codeshare.io/5RJwZ4 LinkedList ADT to store student records(code is below). Using LinkedList ADT instead of the Python List. You will need to use the Student ADT(code is below) Imports the Student class...

  • PYTHON. Continues off another code. I don't understand this. Someone please help! Comment the lines please...

    PYTHON. Continues off another code. I don't understand this. Someone please help! Comment the lines please so I can understand LinkedList ADT: class myLinkedList:     def __init__(self):         self.__head = None         self.__tail = None         self.__size = 0     def insert(self, i, data):         if self.isEmpty():             self.__head = listNode(data)             self.__tail = self.__head         elif i <= 0:             self.__head = listNode(data, self.__head)         elif i >= self.__size:             self.__tail.setNext(listNode(data))             self.__tail = self.__tail.getNext()         else:             current = self.__getIthNode(i - 1)             current.setNext(listNode(data,...

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