Try to sort the array in ascending order so that the first element of the array is from 20,30,10 to 10,20,30 as follows:
[20, 3] [10, 2] [30, 1] → [20, 3] [10, 2] [30, 1]
Lists that have arrays as elements can be sorted using Comparator in Java. (Other lambda expressions can be used.)
Comparator
Comparator<int[]> comparator = new Comparator<int[]>() {
@Override
public int compare(int[] o1, int[] o2) {
return Integer.compare(o1[0], o2[0]);
}
};
You can use a class that implements the Comparator interface to create something like a criteria for comparing magnitudes. This defines a comparison of the size of the array.
comparator<int[]> comparator = new comparator<int[]>() {};
In the part, create an instance of the class that implements the comparator interface and define the method at the same time.Anonymous classIs used.
@override
Method beingpublic int compare(int[] o1,int[] o2) {}
Defines a compare method that compares the magnitude of o1 and o2 of an int type array.
return Integer.compare(o1[0], o2[0])Depending on the size of the int type array o1 and o2, o1[0]And o2[0]It was defined by the size of.
From the above, we were able to generate a comparator with the size of the 0th element of the array ** as the criterion for the size of the array **.
You can sort a list whose elements are arrays by adding the comparator defined earlier to the sort argument.
```java
Collections.sort(list, comparator);
List<int[]> list = new ArrayList<int[]>();
int[] a = {20, 3};
int[] b = {30, 1};
int[] c = {10, 2};
list.add(a);
list.add(b);
list.add(c);
//[20, 3]
//[30, 1]
//[10, 2]
Comparator<int[]> comparator = new Comparator<int[]>() {
@Override
public int compare(int[] o1, int[] o2) {
return Integer.compare(o1[0], o2[0]);
}
};
Collections.sort(list, comparator);
for (int i=0;i<list.size();i++) {
System.out.println(Arrays.toString(list.get(i)));
}
//[10, 2]
//[20, 3]
//[30, 1]
Comparator<int[]> comparator = new Comparator<int[]>() {
@Override
public int compare(int[] o1, int[] o2) {
return Integer.compare(o1[1], o2[1]);
}
};
Collections.sort(list, comparator);
//[30, 1]
//[10, 2]
//[20, 3]
Comparator<int[]> comparator = new Comparator<int[]>() {
@Override
public int compare(int[] o1, int[] o2) {
return Integer.compare(o2[0], o1[0]);
}
};
Collections.sort(list, comparator);
//[30, 1]
//[20, 3]
//[10, 2]
It often appears in AtCoder.
Recommended Posts