有没有一种简单的方法可以将对象移动到数组中以便它们相邻?

时间:2020-05-12 19:19:59

标签: java arrays

我正在研究一个问题,该问题在大小为7的数组中提供了一个对象数组(4个对象),因此有3个空值。数组被加扰。我需要合并元素,以便它们以相同的顺序位于数组的0、1、2、3空间中。空值必须放在数组的末尾的空间4,5,6上。 这是我到目前为止的内容:

let Source = Excel.CurrentWorkbook(){[Name="Table1"]}[Content],
#"Changed Type" = Table.TransformColumnTypes(Source,{{"Date", type date}}),
#"Sorted Rows" = Table.Sort(#"Changed Type" ,{{"ID", Order.Ascending}, {"Date", Order.Descending}}),
#"Added Index" = Table.AddIndexColumn(#"Sorted Rows" , "Index", 0, 1),
#"Added Custom" = Table.AddColumn(#"Added Index" , "Custom", each if [Index]=0 then null else if [ID] = #"Sorted Rows"{[Index]-1}[ID] and [Score] = #"Sorted Rows"{[Index]-1}[Score] then "remove" else null),
#"Filtered Rows" = Table.SelectRows(#"Added Custom", each ([Custom] = null)),
#"Removed Columns" = Table.RemoveColumns(#"Filtered Rows",{"Index", "Custom"})
in #"Removed Columns"

4 个答案:

答案 0 :(得分:2)

如果可以创建一个长度相同但结尾为空值的单独数组,则可以如下所示非常简单:

int j=0;
Car[] newCars = new Car[cars.length];
for(int i=0; i<cars.length; i++) {
    if(cars[i] != null) 
        newCars[j++] = cars[i];
}

答案 1 :(得分:1)

1. Have two variables i = 0, j = last element of array
2. Repeat
      Move i till you get a null object
      Move j till you get a non null object
      swap value of i and j
      If i <= j then break

希望有帮助。

要保持相同的顺序

1. Have two variables i = 0, j = 0
2. Repeat
      Move i till you get a null object
      j = i+1
      Move j till you get a non null object
      swap value of i and j
      Either i or j reaches end of the element then break

1 null 2 3 null

i =>在索引= 1处为空

j =索引= 2

===

1 2 null 3 null

我在索引= 2处发现空值,就像在索引= 1处一样

j发现3

1 2 3 null null

答案 2 :(得分:1)

Alternativley,您可以像下面这样使用Arrays#sort

Arrays.sort(cars, new Comparator<Car>() {
        @Override
        public int compare(Car c1, Car c2) {
            if (c1 == null && c2 == null) {
                return 0;
            }
            if (c1 == null) {
                return 1;
            }
            if (c2 == null) {
                return -1;
            }
            return Arrays.asList(cars).indexOf(c1)-Arrays.asList(cars).indexOf(c2);
        }
    });

答案 3 :(得分:0)

这似乎可行:

Integer[] cars = {null, null, 1, null, 2, 3, 4};
int nums = 4;
for (int i = 0; i < nums; i++) {
    if (cars[i] != null) {
        continue;
    }
    int j = i + 1;
    while(j < cars.length - 1 && cars[j] == null) {
        j++;
    }
    cars[i] = cars[j];
    cars[j] = null;
}