2015-04-12 132 views
-3

我正在写一个Java代码,应该删除arraylist中的所有“0”,并返回一个新的列表,但是没有“0”。替代(?)Java解决方案| ArrayList

举一个例子:

public static void main(String[] args) { 
    int[] sound = {0, 0 , 0, 0, -14, 120, 67, -234, -15, -389, 289, 178, -437, 33, 15, 0, 0, -32, 230, 368}; 
    int[] result = trimSilenceFromFront(sound); 
    System.out.println(Arrays.toString(result)); 
} 

应该是:

[-14, 120, 67, -234, -15, -389, 289, 178, -437, 33, 15, 0, 0, -32, 230, 368] 

我这样做代码:

import java.util.*; 

public class NoZero { 
    public static int[] trimSilenceFromFront(int[] samples) { 
     int[] newArrayList = new int[samples.length]; 

     for (int i = 0; i < samples.length; i = i + 1) { 
      if (samples[i] != 0) { 
       newArrayList.add(samples); 
      } 
     } 
     return newArrayList; 
    } 
} 

当我看了看回答他们不得不同时与混合循环循环。但是由于有多种解决方法:我的代码是否错误?

更新:我误解了这个问题。我认为它应该删除所有的“0”。但正如你可以看到的结果,它应该只在开始时消除沉默。

谢谢大家!

+4

有10000点的方式来做到这一点。解决方案的数量与代码的正确性有何关系? – Maroun

+0

'int [] newArrayList = new int [samples.length];'这会创建一个新的_array_而不是'ArrayList'。另外'newArrayList.add(samples);'这会尝试将整个'samples'数组添加到'newArrayList',而不仅仅是'samples [i]' –

+2

'newArrayList'的值是'int []',你不能使用'add'就可以了。它不是*数组列表。 – Maroun

回答

1

你必须找到第一个非零值,并从该索引到副本的副本。有很多方法可以做到这一点,例如:

public static int[] trimSilenceFromFront(int[] samples) { 
    int i = 0; 
    while (i++ < samples.length) { 
     if (samples[i] != 0) { 
      break; 
     } 
    } 
    return Arrays.copyOfRange(samples, i, samples.length); 
} 
0

有无数种方法可以解决Java问题。单一解决方案的可行性可以用不同的方式来衡量。

我发现最大的测量是代码可读性,可维护性,内存使用和执行速度。考虑你的要求,并尽量平衡这些衡量标准。

0

@Bubletan的解决方案是迄今为止效率更高的解决方案。

如果想要另一个解决方案,您也可以把它的工作原理与链表:

private static Integer[] trimSilenceFromFront(Integer[] samples) { 
    LinkedList<Integer> soundList = new LinkedList<Integer>(Arrays.asList(samples)); 
    boolean soundStarted = false; 
    while(!soundStarted && soundList.size()>0){ 
     if(soundList.peekFirst()!=null && soundList.peekFirst()==0){ 
      soundList.removeFirst(); 
     } 
     else { 
      soundStarted=true; 
     } 
    } 
    return soundList.toArray(new Integer[0]); 
} 
0

编辑:

没关系,这一切修剪从沉默范围,不只是从正面。对不起,你的问题和代码相互矛盾。


这是一个混乱的解决方案,我想,但可能会导致你在正确的道路

 int[] sound = {0, 0 , 0, 0, -14, 120, 67, -234, -15, -389, 289, 178, -437, 33, 15, 0, 0, -32, 230, 368}; 

     ArrayList<Integer> temp = new ArrayList<Integer>(); 

     for(int i = 0; i < sound.length; i++) { 
      if(sound[i] != 0) { 
       temp.add(sound[i]); 
      } 
     } 

     int[] trimmedSound = new int[temp.size()]; 

     for(int i = 0; i < temp.size(); i++) { 
      trimmedSound[i] = temp.get(i); 
     } 
     System.out.println(Arrays.toString(sound)); 
     System.out.println(Arrays.toString(trimmedSound)); 
    } 

这是输出

[0, 0, 0, 0, -14, 120, 67, -234, -15, -389, 289, 178, -437, 33, 15, 0, 0, -32, 230, 368] 
[-14, 120, 67, -234, -15, -389, 289, 178, -437, 33, 15, -32, 230, 368]