I have write this program for "Reversing array and after reversing not showing duplicate elements", but it prints just till second last element:
int[] a = new int[] { 1, 2, 3, 4, 5, 5, 6, 7, 8, 9, 10 };
for (int i = 0; i < a.Length / 2; i++)
{
int tmp = a[i];//Getting First/current element
a[i] = a[a.Length - i - 1];//Getting last Element and assigning to first/current
a[a.Length - i - 1] = tmp;
}
int j=0;
for(int i=0;i< a.Length;i++)
{
j=i+1;
if(j < a.Length)
{
if (a[i] != a[j])
Console.WriteLine(a[i]);
}
j++;
}
Run Code Online (Sandbox Code Playgroud)
What am I doing wrong?
It'*_*ie. 11
你做错了是不使用LINQ:
foreach (int i in a.Reverse().Distinct())
{
Console.WriteLine(i);
}
Run Code Online (Sandbox Code Playgroud)
但是,由于您似乎想手动执行此操作,因此这是一个实现:
IEnumerable<T> Reverse<T>(this IList<T> arr)
{
if (arr == null) throw new ArgumentNullException();
for(int i = arr.Count - 1; i > 0; i--) yield return arr[i];
}
IEnumerable<T> Distinct<T>(this IEnumerable<T> list)
{
Hashset<T> tmpHash = new Hashset<T>();
foreach (T item in list) tmpHash.Add(item);
return tmpHash;
}
//your method is now simple as:
a.Reverse().Distinct(); //hey, looks like LINQ but I've implemented it myself.
Run Code Online (Sandbox Code Playgroud)
试试这个 :
var arr = new int[] {1,2,4,5,6,4,5};
var tmp = arr.Reverse().Distinct();
Run Code Online (Sandbox Code Playgroud)
希望这个帮助.