Win a copy of Learning OpenStack Networking: Build a solid foundation in virtual networking technologies for OpenStack-based clouds this week in the Cloud/Virtualization forum!
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
• Liutauras Vilda
• Campbell Ritchie
• Tim Cooke
• Bear Bibeault
• Devaka Cooray
Sheriffs:
• Jeanne Boyarsky
• Knute Snortum
• Junilu Lacar
Saloon Keepers:
• Tim Moores
• Ganesh Patekar
• Stephan van Hulst
• Pete Letkeman
• Carey Brown
Bartenders:
• Tim Holloway
• Ron McLeod
• Vijitha Kumara

# Can i do better than this

Greenhorn
Posts: 5
This is code snippet for finding the first Unique Char in a Array of Chars or String, can i do Better than, this. Do let me know, just curious. This is not a homework for me, just trying to keep my Brain engaged .

public char getFirstUniqueChar(char ary[]) {

char unique = '0';
for(int i =0; i < ary.length; i++) {

boolean found = false;

for(int j = 0; j < ary.length; j++) {

if(i != j && ary[i] == ary[j]){
found = true;
break;
}
}

if(!found) {
unique = ary[i];
break;
}

}

return unique;

}

Sheriff
Posts: 23706
50
Depends on what "better" means. An obvious improvement is that the inner loop only needs to start at i+1, not at zero. But you have an O(N^2) algorithm, and there exists an O(N) algorithm which is more complex and needs to store working data somewhere.

HariHaran Rama
Greenhorn
Posts: 5
Hi Paul,

Thanks for the response,

"better" is either faster or smarter for me, i thought of starting j at i+1, but there is a problem there, if you have a String like ABBAC, j=i+1 in the inner for loop will not work. do you agree ?, let me know.

Paul Clapham
Sheriff
Posts: 23706
50
I don't have to have an opinion about whether it works or not. Or rather, my opinion is worthless. Either it works or it doesn't, and you can determine that by testing.

So, does it work? If not, why not?

Ranch Hand
Posts: 47
If you are using java 5, you can use modified for loop, its much easier:

havnt tried running it. You can also use Set interface to remove duplicate items.Its mucs simpler coding wise. If looking for simpler code, then Set provides a better answer. Performance wise may not necessarily be.

 With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.