繁体   English   中英

如何在Java中剪切数组的一部分

[英]How can I cut a section of an array in java

我必须用Java编写一个方法,在其中输入一个数字数组“ a”,然后输入一个数字“ x”返回一个元素数组,该元素数组遵循“ a”中“ x”的最后一次出现。 例如,对于输入{0,1,2,3,4,5,6,7,8,9}和x = 6,该方法必须返回{7,8,9}同时具有{4,1,4,2 }和x = 4,该方法必须返回{2},如果x不在“ a”中,则它必须返回空数组{}(或长度为0的数组)

到目前为止,我们还没有研究类或对象。这里是到目前为止我们制作的另一个程序的示例

boolean arrayIncluso( int[] s,int[] t ) {

boolean flag=true;
for(int i=0;i< s.length;i++){
    int c1 = 0 ;
int c2 = 0 ;
    for(int j=0;j< s.length;j++){
        if(s[i] == s[j]){
            c1 ++;
        }
    }

    for(int j=0;j< t.length;j++){
        if(s[i] == t[j]){
            c2 ++;
        }
    }

    if(c1 > c2)

    flag= false; 
}
return flag;
}

有人可以向我解释为什么

t[i-idx-1 ] = s[i];

代替这个

     for(int j=0;j<t.length;j++){
     t[j]=a[i];
}
return t;

您可以将问题分为两部分:

  1. 查找字符x最后一个索引。 可以使用easy for循环来完成。

     int idx = -1; for (int i = 0; i < s.length; i++) { if (s[i] == x) idx = i; } 
  2. 找到该索引后,从该元素开始创建一个新数组。 可以使用第二个(非嵌套的)for循环来完成,也可以使用Arrays.copyOfRange()

     //make sure idx != -1 int[] t = new int[s.length - idx - 1]; for (int i = idx+1; i < s.length; i++) t[i-idx-1 ] = s[i]; System.out.println(Arrays.toString(t)); //print to make sure it's all fine 

要么

    t = Arrays.copyOfRange(s, idx+1, s.length);
    System.out.println(Arrays.toString(t));

这是一个通用算法:(您必须自己编写代码)

  1. 遍历数组,跟踪数字x的当前索引。 将此索引称为eglastOccurance。
  2. 从lastOccurance + 1开始返回数组。

不要忘记检查是否发生任何事件,以及最后发生的事件是否是数组结尾。

使用清单:

int pos = a.lastIndexOf(x);
List<Integer> result = null;
if(pos > -1)
   result = a.subList(pos+1, a.size());

您可以使用Arrays从各种方法构建列表:

Integer [] array = new Integer[3];
...
...
List<Integer> a = Arrays.asList(array);

一起将导致如下代码:

List<Integer> a = Arrays.asList(array);
int pos = a.lastIndexOf(x);
int [] result = null;
if(pos > -1) {
    List<Integer> sl = a.subList(pos+1, a.size());
    result = new int[sl.size()];
    for(int i = 0; i < sl.size(); i++)
        result[i] = sl.get(i);
}

您可以使用commons lang库来使用ArrayUtils.lastIndexOf方法确定数组元素的最后一个索引,这样它就变成了单行代码:

int[] t = Arrays.copyOfRange(s, ArrayUtils.lastIndexOf(s, x) + 1, s.length);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM