# My Java algorithm looks right, but it is not

• Hi,

Just getting started with this website.

I have included some print statements there for debugging purposes. I think my algorithm's logic is sound, but apparently, it is not. Could someone point me in the right direction?

Many thanks.

``````public class Solution
{
boolean found = false;

public int hIndex(int[] citations)
{
if (citations.length == 0) return 0;
else if (citations.length == 1){
if (citations[0] == 0) return 0;
return 1;
}
Arrays.sort(citations);

int numOfPapers = citations.length;// to get total number of papers

int index;

// mapping papers from 1 to numOfPapers with their associated number of citations
HashMap<Integer, Integer> papersCitations = new HashMap<Integer, Integer>();

for (int p = 1; p <= numOfPapers; p++)
{
papersCitations.put(p, citations[p-1]);
}

//System.out.println("papersCitations: " + papersCitations);

int i = 0;
while (found == false && i != citations.length)
{
index = citations[citations.length-i-1];
while (index > numOfPapers)
{
index = citations[citations.length-(++i)-1];
}

System.out.println("index: " + index);

int countOfPapersWithWantedCitation = 0;
int countOfPapersWithNoMoreThanWantedCitation = 0;

for (Integer key : papersCitations.keySet())
{
int value = papersCitations.get(key);
if (value <= index) countOfPapersWithNoMoreThanWantedCitation++;
if (value >= index) countOfPapersWithWantedCitation++;
}

System.out.println("Count of papers with wanted citation: " + countOfPapersWithWantedCitation);
System.out.println("Count of papers with no more than wanted citation: " + countOfPapersWithNoMoreThanWantedCitation);

if ((countOfPapersWithWantedCitation == index) && ((numOfPapers - index) <= index))
{
found = true;
}

i++;
System.out.println(found);
}
if (result.isEmpty()) return 0;
return Collections.max(result);
}

}
``````

inputs with incorrect outputs:
[1,1] = 0, instead of 1
[10,9,8,7,6,5,4,3,2,1] = 0, instead of 5
[0, 1, 16, 15, 15, 16, 8, 3, 5, 6, 7, 8, 30000, 500, 55, 200] = 0 instead of 8

I am sure there are many others.

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