-1

我需要一些帮助才能做到这一点,

问题 写一个函数,它需要两个数组——一个数组是源数组,另一个数组是索引数组,并删除源数组索引处的所有元素,并从第二个数组中获取索引。

这就是我想出的......

 public static int[] DeleteArrayUsingIndices(int[] source, int[] indices)
    {
        for (int i = 0; i < indices.Length; i++)
        {
            if (indices[i] < source.Length)
            {
                source[indices[i]] = int.MinValue; // delete
            }                
        }

        return source;
    }

我不太确定这个解决方案,因为这不会删除该值。谁能帮我解决这个问题。

4

2 回答 2

2

你不能真正从数组中删除元素,所以你需要问这个措辞是什么意思。如果用特殊元素(如int.MinValue您的代码)替换元素是可以接受的,那么您的解决方案就可以了。

另一种解释可能是重新排列数组,以便“未删除”索引以与原始顺序相同的顺序位于数组的开头——在这种情况下,您将希望返回数组的新“长度”(未“删除”的元素的数量)——这意味着“删除”操作会将尚未删除的元素的数组压缩到数组的开头(将数组的内容从已删除的元素移向开头数组末尾的索引(或未删除元素的末尾)。注意不要“删除”同一个元素两次。

要实现后者,您将必须跟踪哪个位置移动了多少元素。或者,更新索引数组以减少比当前更大的索引(以容纳现在压缩的数组)——在这种情况下,您可以从对索引数组进行排序开始(可能同时删除重复项)并跟踪如何到目前为止,许多职位已经转移

于 2012-06-18T16:53:37.883 回答
1

尝试这个

public static void main(String[] args) {
    Integer[] a = {1,2,3,4,5,6,7,8,9};
    Integer[] b = {2,3};
    System.out.println(Arrays.asList(deleteArrayUsingIndices(a, b)));
}

^ 用于测试

public static Integer[] deleteArrayUsingIndices(Integer[] source, Integer[] indices)
{
    ArrayList<Integer> sourceArr = new ArrayList<Integer>(Arrays.asList(source));
    ArrayList<Integer> toDelete = new ArrayList<Integer>();
    for (int i:indices)
    {
        try {
            toDelete.add(sourceArr.get(i));
        } catch (Exception e) {}              
    }

    sourceArr.removeAll(toDelete);

    return sourceArr.toArray(new Integer[sourceArr.size()]);
}
于 2012-06-18T16:52:09.040 回答