有一个问题给了我一个随机数作为一个枢轴,我必须将我的数组w.r.t排序到这个枢轴(最近先来,然后最远)。
array =[2,7,4,6,4,4,5,3,6,9,1,1,9] and
pivot=5
expected output: [5,4,4,6,6,3,7,2,1,1,9,9]这有可能是计数排序的变化吗?如果不是!有人能给我一个解决这个问题的线索吗?在思考如何处理计数和数组索引时,我遇到了一个障碍,因此,到目前为止,我已经能够做到这一点。
class HelloEclipse{
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int N=sc.nextInt();
int pivot=sc.nextInt();
int[] mainArray=new int[N];
int[] differenceArray=new int[N];
int[] differnceCountArray=new int[Integer.MAX_VALUE];
for(int i=0;i<N;i++){
mainArray[i]=sc.nextInt();
differenceArray[i]=pivot-mainArray[i];
if(differenceArray[i]>0){
differnceCountArray[differenceArray[i]]++;}
else{
differnceCountArray[-differenceArray[i]]++;
}
}
}
}任何关于如何进行的建议都是有帮助的!
发布于 2016-09-18 12:15:58
编写一个合适的整数比较器并使用Arays.sort:
public class PivotComparator implements Comparator<Integer> {
private int pivot;
public PivotComparator(int pivot) {
super();
this.pivot = pivot;
}
@Override
public int compare(Integer a, Integer b) {
return Math.abs(a - pivot) - Math.abs(b - pivot);
}
public static void main(String[] args) {
Integer[] toSort = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
Comparator<Integer> comp = new PivotComparator(5);
Arrays.sort(toSort, comp);
for (Integer i : toSort) {
System.out.println(i);
}
}
}编辑
要把所有的四分放在六号前面,你可以做(而不是两次排序)。
public int compare(Integer a, Integer b) {
int diff = Math.abs(a - pivot) - Math.abs(b - pivot);
if (diff != 0) {
return diff;
}
return a - b;
}发布于 2016-09-18 12:21:14
下面是一个实现
int[] array = { 2, 7, 4, 6, 4, 4, 5, 3, 6, 9, 1, 1, 9 };
int pivot = 5;
int[] sorted = Arrays.stream(array).boxed().sorted().sorted((i1, i2) -> Math.abs(i1 - pivot) - Math.abs(i2 - pivot)).mapToInt(i -> i).toArray();
System.out.println(Arrays.toString(sorted));输出
[5, 4, 4, 4, 6, 6, 3, 7, 2, 1, 1, 9, 9]https://stackoverflow.com/questions/39557402
复制相似问题