2016-08-12 80 views
-2

是否有方法可以用數組中的一個項替換兩個彼此相鄰的項。用數組中的一個項替換兩個彼此相鄰的項目

在陣列是這樣的:

int[] array = new int[]{ 1, 2, 2, 3, 3, 4, 5, 3, 2 }; 

除去它們是彼此相鄰的相同的項目,從而導致成這樣:

{ 1, 2, 3, 4, 5, 3, 2 }; 

編輯: 這裏我結束:

int[] array = new int[]{ 1, 2, 2, 3, 3, 4, 5, 3, 2 }; 
int last = 0; 
List<int> Fixed = new List<int>(); 
foreach(var i in array) 
{ 
    if(last == 2 && i == 2 || 
     last == 3 && i == 3) 
    { 
    } 
    else 
    { 
     Fixed.Add(i); 
     last = i; 
    } 
} 
return Fixed.ToArray() // Will return "{ 1, 2, 3, 4, 5, 3, 2 }" 

但我必須輸入所有th e我想要跳過...

+0

是的。你有什麼嘗試? – user1620220

+0

有很多方法可以做到這一點。你有嘗試過什麼嗎?小提示:你不能縮小數組,所以你需要分配一個新的數組。 – dasblinkenlight

+0

您可能想從http://stackoverflow.com/questions/457453/remove-element-of-a-regular-array開始 –

回答

1
int[] array = new int[] { 1, 2, 2, 3, 3, 4, 5, 3, 2 }; 
//int[] output = array.Distinct().ToArray();Use this line if you want to remove all duplicate elements from array 
int j = 0; 
while (true) 
{ 
    if (j + 1 >= array.Length) 
    { 
     break; 
    } 
    if (array[j] == array[j + 1]) 
    { 
     List<int> tmp = new List<int>(array); 
     tmp.RemoveAt(j); 
     array = tmp.ToArray(); 
    } 
    j++; 
}