2011-03-13 57 views
1

我想從數組中提取特定索引值,並將它們放入新數組中。主陣列的值如下:嵌套循環提取索引值到新陣列中

int a[] = {7, 8, 9, 9, 8, 7}; 

我提出的方法的調用如下:

print(findAll (a,7)); 
print(findAll (a,2)); 

我使用的方法如下:

public int[] findAll(int a[], int target) 
    { 
     int count = 0; 
     int i = 0; 
     int index = 0; 
     int spotIndex = 0; 


     for (i = 0; i < a.length; i++) 
     { 
      if (a[i] == target) 
      count = count + 1; 
      spotIndex = i; 
     }   

     int result[] = new int[count]; 

     for (index = 0; index < count; index++) 
     { 
      result[index] = spotIndex; 
      index++; 

     } 
     return result; 
    } 

結果應該是:

{0,5} {}

我的結果如下;如果我改變目標參數,我會得到相同的結果。

{5,0} {}

在此先感謝....

回答

0

spotIndex沒有服務你覺得需要爲宗旨。

for (i = 0; i < a.length; i++) 
{ 
     if (a[i] == target) 
     count = count + 1; 
     spotIndex = i;  // spotIndex comes in for loop but not in if condition. 
          // and this gets modified at every step in loop. 
          // simply assigning value of i to it. 
} 

代替邏輯應該是 -

for (i = 0; i < a.length; i++) 
{ 
     if (a[i] == target) 
     count = count + 1; 
} 

count給出了次重複target數。現在,創建一個大小爲count的數組,以實際將這些元素的索引複製到數組中。

int result[] = new int[count]; 
int copyIndex = 0; 
for (index = 0; index < a.length; index++) 
{ 
    if(a[index] == target) 
    { 
      result[copyIndex] = index ; 
      ++copyIndex; 

      if(copyIndex == count) 
       return result ;    
    } 
} 

我在第一個循環中看不到使用此語句 - spotIndex = i;

注意:邏輯假定搜索元素(即target)肯定存在於數組中。儘管稍作修改,但如果元素僅存在,我們可以返回索引。

+0

太棒了,非常感謝解釋!湯姆 – user592646 2011-03-13 03:37:31

1

小編建議:

for (index = 0; index < count; index++) 
{ 
    result[index] = spotIndex; 
    index++; 
} 

您指數++調用雙倍。這是不好的做法,在方法範圍內使用索引,更好的是:

for (int index = 0; index < count; index++) 
{ 
    result[index] = spotIndex; 
} 

注意,你把spotIndex(相同值)中的所有結果的要素。

爲什麼你不使用列表?

public Integer[] findAll(int a[], int target) { 
    List<Integer> result = new ArrayList<Integer>(); 
    for (int i=0; i<a.length; i++) { 
     if (a[i] == target) { 
      result.add(i); 
     } 
    }  
    return result.toArray(new Integer[result.size()]); 
}