2015-04-12 187 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]