2012-06-18 58 views
-1

我需要得到這個權利一些幫助,刪除重複的整數 - 僞代碼

問題 寫一個函數這需要2 arrays-一個陣列是源陣列和其它陣列是使用第二個數組中的索引刪除所有存在於源數組索引處的元素。

這是我想出了....

public static int[] DeleteArrayUsingIndices(int[] source, int[] indices) 
    { 
     for (int i = 0; i < indices.Length; i++) 
     { 
      if (indices[i] < source.Length) 
      { 
       source[indices[i]] = int.MinValue; // delete 
      }     
     } 

     return source; 
    } 

我不是很確定這個解決方案,因爲它不會刪除值。任何人都可以幫助我解決這個問題。

回答

2

你真的不能從一個數組中刪除元素,所以你要問什麼是通過這樣的措辭的意思。如果用異常元素(如代碼中的int.MinValue)替換元素是可以接受的,那麼您的解決方案就沒有問題。

另一種解釋可能是重新排列數組,使「未刪除」索引在數組開頭的位置與原來的順序相同 - 在這種情況下,您希望返回新的「長度」 (未被刪除的元素數量) - 這意味着「刪除」操作會將尚未刪除元素的數組壓縮到數組的起始位置(將數組內容移向從刪除的索引開始到數組的末尾(或者到非刪除元素的末尾),必須注意不要「刪除」兩次相同的元素

爲了實現後者,您將擁有或者跟蹤哪個位置被多少個元素移動,或者更新索引數組t o遞減大於當前值的指數(以容納現在緊湊的數組) - 在這種情況下,您可以通過對索引數組進行排序(可能同時刪除重複數據)並只記錄多少位置已經移動遠

1

試試這個

public static void main(String[] args) { 
    Integer[] a = {1,2,3,4,5,6,7,8,9}; 
    Integer[] b = {2,3}; 
    System.out.println(Arrays.asList(deleteArrayUsingIndices(a, b))); 
} 

^測試

public static Integer[] deleteArrayUsingIndices(Integer[] source, Integer[] indices) 
{ 
    ArrayList<Integer> sourceArr = new ArrayList<Integer>(Arrays.asList(source)); 
    ArrayList<Integer> toDelete = new ArrayList<Integer>(); 
    for (int i:indices) 
    { 
     try { 
      toDelete.add(sourceArr.get(i)); 
     } catch (Exception e) {}    
    } 

    sourceArr.removeAll(toDelete); 

    return sourceArr.toArray(new Integer[sourceArr.size()]); 
}