2016-03-16 31 views
1

我正在实现我的自定义ArrayList类的整数与数组的帮助下,我想能够从我的数组中删除一个特定的值。我的问题是,当有多个相同的可删除值彼此相邻时,我会得到两个相邻的0,从而导致错误。我试图解决它几个小时没有运气。这里是我的代码:如何实现自定义ArrayList的deleteValues(int values)方法?

int max=10; 
    public int[] a = new int[max]; 

    @Override 
    public void deleteValues(int value) { 
    int tempIndex=0; 

    for (int i = 0; i <50 ; i++) { 
     if (a[tempIndex] == value) { 
      a[tempIndex] = a[tempIndex + 1]; 
      a[tempIndex + 1] = 0; 
     } else if (a[tempIndex] == 0) { 
      a[tempIndex] = a[tempIndex + 1]; 
      a[tempIndex + 1] = 0; 

     } else { 
      tempIndex++; 

     } 

    } 


} 

我的阵列看起来像删除值(4)前:

[4, 2, 3, 4, 4, 4, 4, 1, 2, 3] 

这是运行代码后的错误的结果:

[2, 3, 0, 0, 4, 4, 4, 1, 2, 3] 

什么我想实现:[2, 3, 1, 2, 3, 0, 0, 0, 0, 0]

我的问题是:什么是最好的方法来ma关注代码工作,尽可能少地使用循环?

+3

哪里'ArrayList'?什么是'a'? – Maroun

+0

对不起,a是一个数组,我尝试实现自己的Arraylist类。 – codeme

+0

你想从数组中删除元素还是将其设置为0? – Slavik

回答

0

您代码中的问题之一是,您总是将索引tempIndex+1中的元素复制到tempIndex:它总是下一个元素。 事实上,在删除之后,我们假设数组中的元素为5,那么您必须将tempIndex+5复制到tempIndex

我认为这是做这件事的好方法:

public void deleteValues(int[] a, int value) { 
    int j=0; 
    for(int i=0; i<a.length; i++) { 
     if(a[i]!=value) { 
      a[j] = a[i]; 
      j++; 
     } 
    } 
    // fill the rest of the array with zeros 
    while(j<a.length) { 
     a[j] = 0; 
     j++; 
    } 
} 

基本上,你把两个指标:ij。 索引i遵循“原始”数组,而索引j在“新”数组之后(删除之后)。 指数i遍历所有元素:如果a[i]等于value,将其复制到新的位置j和增量都ji。如果a[i]等于value,则跳过它并增量i而不递增j。 在复制或跳过所有元素后,用数字0填充数组的末尾。

样品输入:

a  = {4, 2, 3, 4, 4, 4, 4, 1, 2, 3} 
value = 4 

输出:

a  = {2, 3, 1, 2, 3, 0, 0, 0, 0, 0} 
0
public static void deleteValues(int[] a, int value) { 
    int newSize = a.length; 
    int current = 0; 
    for (int i = 0; i < a.length; i++) { 
     if (a[i] != value) { 
      if (i != current) { 
       a[current] = a[i]; 
       newSize--; 
      } 
      current++; 
     } 
    } 
    //use first newSize values, for example you can copy to new array 
    System.out.println("New size = " + newSize); 
} 
0

你可以使用迭代器:

List<Integer> numbers = .... 
Iterator<Integer> i = numbers.iterator(); 
while (i.hasNext()) { 
    Integer num = i.next(); 
    // add here your custom code 
    i.remove(); 
} 
0
  int tempIndex,index; 
      for (index = 0, tempIndex = 0; index < valuesArray.length; index++) { 
       if (valuesArray[index] != valToDelete) { 
        valuesArray[tempIndex++]=valuesArray[index]; 
       } 
      } 
      while(tempIndex<valuesArray.length){ 
       valuesArray[tempIndex++]=0; 
      } 
相关问题