2013-12-08 31 views
2

以下代碼編譯並執行我所需的操作。它遍歷基於int的多維數組(稱爲nums),並搜索值爲1的所有事件。該程序的輸出如下所示。有三件事要注意:高效循環代碼?此外,關於「for each」循環的查詢

  • 關於「outer for」循環語句,我使用Java的逗號運算符來聲明兩個附加變量。
  • 另外關於這個「outer for」,我在「迭代部分」中使用了另一個逗號操作符來重置其中一個附加變量。
  • 關於「inner for」,我在「迭代部分」中使用了另一個逗號運算符來增加這個附加變量。
int[][] nums = {{1,1,2},{3,4},{5},{6,7,8},{9,1,1}}; 

for (int i=0, elsSearched=0, foundCount=0; i < nums.length; i++, elsSearched=0) { 
    for (int j=0; j < nums[i].length; j++, elsSearched++) { 
     if (nums[i][j] == 1) { 
      foundCount++; 
     } 
    } 
    System.out.println("Searched " + elsSearched + 
" elements, and found \'number one\' a total of " + foundCount + " times.."); 
}  

程序輸出:

Array search results

難道這代碼更effeciently /文筆優美?

我的另一個查詢是關於Java的「for each」循環。我嘗試用逗號操作符的「for each」循環重寫上面的代碼,但代碼不會編譯。我很快得出了一個明顯的結論,但是如果逗號操作符可以與它一起使用,那麼「for each」循環會更好嗎,還是會引入「干擾雜亂」?

+0

我不認爲你可以更有效地做到這一點,因爲你必須看看每個元素至少一次,以告訴它是否是一個;) – Blub

+0

另請參見[這個答案](http://stackoverflow.com/a/256861/202504)有關每個循環與循環的效率。 – jmiserez

回答

2

編輯:請注意,foundCount是發現的元素的總數直到現在,因爲它永遠不會重置爲零。這是打算?

難道你不同意這段代碼更容易閱讀和更簡潔嗎? (注:效率是一樣的代碼)

int[][] nums = {{1,1,2},{3,4},{5},{6,7,8},{9,1,1}}; 

int foundCount = 0; 
for(int[] inner : nums){ 
    for(int i : inner){ 
     if (i == 1){ 
      foundCount++; 
     } 
    } 
    System.out.println("Searched " + inner.length + 
       " elements, and found \'number one\' a total of " + foundCount + " times.."); 
} 

輸出:

Searched 3 elements, and found 'number one' a total of 2 times.. 
Searched 2 elements, and found 'number one' a total of 2 times.. 
Searched 1 elements, and found 'number one' a total of 2 times.. 
Searched 3 elements, and found 'number one' a total of 2 times.. 
Searched 3 elements, and found 'number one' a total of 4 times.. 
+1

非常好,謝謝。是的,「foundCount」功能就像預期的一樣,是的,我同意你的意見,即你的代碼更容易閱讀,也更簡潔。謝謝。 – user2911290

1

首先,你可能不應該優化的東西,直到你已經證明了這是一個顯著貢獻你的程序運行。話雖這麼說,爲什麼不試試這個,而不是...

int foundCount = 0; 
int totalCount = 0; 
for (final int[] i : nums) { // foreach int[] in nums 
    for (final int v : i) { // foreach value v in the int[] from nums 
    switch (v) {    // switch on a constant int... 
    case 1:     // The value we seek. 
     ++foundCount;   // Add to the foundCount, and fall through! 
    default: 
     ++totalCount; 
    } 
    } 
} 
System.out.println("Searched a total of " + totalCount + 
      " elements and found '#1' a total of " + foundCount); 
+0

我很好奇,爲什麼'final'關鍵字?性能優勢還是隻是一個安全網? – jmiserez

+0

是的。當事物不可變時(運行時和編譯器可以優化)以及使用'switch'和'if'時,可以進行優化。 –

+0

不知道只有3個目標的跳轉表,但我同意最後一個。太差的優雅和效率並不總是相同的。 – jmiserez

0

如果你有性能問題,你可以嘗試在子陣列使用二進制搜索(如果你的數組總是排序)。

int valueToSearch = 1; 

for(int[] inner : nums){ 

    int foundIndex = Arrays.binarySearch(inner, valueToSearch); 

     if (foundIndex >= 0){ 
      foundCount ++; 
     } 

} 

因此,您將獲得O(n * log(n))而不是O(n^2)的性能。

我想你必須做一些基準測試。但最重要的是要知道你的輸入是怎樣的。比你可以找到最好的算法。