• Post Reply Bookmark Topic Watch Topic
  • New Topic

Can i do better than this  RSS feed

 
HariHaran Rama
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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;

}
 
Paul Clapham
Sheriff
Posts: 22835
43
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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: 22835
43
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
An Sush
Ranch Hand
Posts: 47
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!