Reputation: 891
Recently I was asked a very tricky question in an interview.
Given an array like (just for example)
Now write an optimized algorithm (without using in build feature except the basic one like for loop etc.) so that the output does not contain duplicate values.
Please Note: Of course we can do it having 2 for loops, but its not optimized. They wanted an optimized solution.
Upvotes: 1
Views: 616
Reputation:
`var stringArray = { "0", "1", "5", "65", "r" }; var uniqueStringArray = stringArray.Distinct().ToArray();
Upvotes: 0
Reputation: 4314
In java you can add all elements into Set
using Collections#addAll()
Set<T> data = new HashSet<T>();
Collections.addAll(data, yourArray);
PS : Set is a collection that contains no duplicate elements.
Upvotes: 0
Reputation: 758
You can use modified merge sort. You represent your array as two arrays, and them merge them, but when you find equal values on merge operation you throw out one of them.
Upvotes: 1
Reputation: 44844
In Java put the Array into Set
see http://docs.oracle.com/javase/7/docs/api/java/util/Set.html
Upvotes: 0
Reputation: 101701
For C# you can do:
var result = new HashSet<string>(yourArray);
Upvotes: 0
Reputation: 15630
In LinQ its possible
strarray = Your array.
strarray.Distinct().ToArray()
Upvotes: 0
Reputation: 60506
In c# just use the System.Linq Distinct
method.
var stringArray = { "0", "1", "5", "65", "r" };
var uniqueStringArray = stringArray.Distinct().ToArray();
Upvotes: 3