嵌套循环将索引值提取到新数组中

时间:2011-03-13 01:56:21

标签: java

我正在尝试从数组中提取特定的索引值,并将它们放入一个新数组中。主要数组值如下:

 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} {}

提前致谢....

2 个答案:

答案 0 :(得分:1)

小建议:

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

你将++调用的索引加倍。在方法范围中使用索引是不好的做法,更好的是:

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

请注意,您将spotIndex(相同的值)放在所有结果元素中。

为什么不使用List?

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()]);
}

答案 1 :(得分: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)肯定存在于数组中。稍微修改一下,如果元素只存在,我们可以返回索引。

相关问题