I want to know the rank of each element in an array, starting at 0.
For example:
arr = {2, 1,3 } rank will be {1,0 ,2}
Explanation:
rank of 2 is 1 because 2 is greater than exactly 1 element rank of 1 is 0 because 1 is greater than exactly 0 element rank of 3 is 2 because 1 is greater than exactly 2 element
What I tried is an n^2 time complexity algorithm. I want an O(n) linear time complexity algorithm.
Someone gave me a solution for this in the comments section below, but his comment was deleted. I do not know how to do that. Which works correctly for negative integers and positive integers, as well as a very large list size.
Thanks to the author
import java.io.IOException; import java.io.InputStream; import java.util.*; class rank{ public static void main(String args[]){ ArrayList<Integer> list = new ArrayList<Integer>(); list.add(2); list.add(1); list.add(3); ArrayList<Integer> listCopy = new ArrayList<Integer>(list); Collections.sort(list); // sorting array // System.out.println("List : " + listCopy); // System.out.println("Sorted List : " + list); Map<Integer, Integer> rankMap = new HashMap<Integer, Integer>(); int counter = 0; for(int x : list) { rankMap.put(x, counter); // list value as key and rank as value. counter++; } StringBuffer sb=new StringBuffer(); for(int x : listCopy) { sb.append(rankMap.get(x) + " "); // System.out.println(map.get(x)); } System.out.println( sb.toString().substring(0, sb.length()-1)) } }
java arrays algorithm time-complexity
Syed shibli
source share