Solution - Slightly Long


  • 0
    S
    class Solution {
        public List<String> topKFrequent(String[] words, int k) {
            List<String> a = new ArrayList<String>();
    		int b[] = new int[words.length];
    		int flag = 0;
    		int i;
    		int total = 0;
    		for (i = 0; i < words.length; i++) {//adding words to the ArrayList and storing the number of repititions and the total number of words
    			if (a.contains(words[i])) {
    				b[a.indexOf(words[i])]++;
    				total++;
    			} else {
    				a.add(words[i]);
    				b[flag] = 1;
    				flag++;
    				total++;
    			}
    		}
    		while (total > 0) {//sorting the values in ascending order based on the number of repititions
    			int sorter[] = new int[100];
    			int counts = 0;
    			int check = 0;
    			List<String> temp = new ArrayList<String>();
    			for (i = 0; i < a.size(); i++) {
    				if (b[i] == total) {
    					sorter[counts] = i;
    					counts++;
    					temp.add(a.get(i));
    					check = 1;
    				}
    			}
    			if (check == 1) {
    				temp.sort(null);
    				for (i = 0; i < temp.size(); i++) {
    					a.set(sorter[i], temp.get(i));
    				}
    			}
    			total--;
    		}
    
    		int z[] = new int[k];
    		int counter = 0;
    		while (k > 0) {//getting the top k frequent elements and storing them in another ArrayList
    			int max = -1;
    			int index = -1;
    			for (i = 0; i < a.size(); i++) {
    				if (b[i] > max) {
    					max = b[i];
    					index = i;
    				}
    			}
    			z[counter] = index;
    			b[index] = 0;
    
    			counter++;
    			k--;
    		}
    		List<String> result = new ArrayList<String>();
    		for (i = 0; i < counter; i++) {
    			result.add(a.get(z[i]));
    		}
    		return result;
        }
    }
    

Log in to reply
 

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