【发布时间】:2017-03-23 09:10:49
【问题描述】:
给定一个数组,我想找出这些元素在排序后的数组中的位置。因此,输入和输出如下所示
Input : {10, 5, 4, 9, 8, 3, 2, 1, 6, 7}
Output: {0, 3, 4, 9, 8, 1, 2, 5, 6, 7}
这意味着,10 将位于已排序数组中的第 0 位,而 5 将位于第四个索引中,即 sortedinput[3]。
这是一个可以做到的单线
Arrays.sort(index, (a, b) -> (nums[b] - nums[a]));
方法如下所示
public Integer[] findIndexInSortedArray(int[] nums) {
Integer[] index = new Integer[nums.length];
for (int i = 0; i < nums.length; i++) {
index[i] = i;
}
Arrays.sort(index, (a, b) -> (nums[b] - nums[a]));
return index;
}
有没有办法在不使用 lambda 和 Java 8 的任何特性的情况下执行与上述相同的操作?是否可以仅使用 Comparator 来实现这一点?
【问题讨论】:
-
10和0th怎么样?不应该是9th -
@buraquete 这取决于订单是降序还是升序。 OP 代码中的当前 lambda 表达式采用降序排列。
-
@Eran 那么
3是1st怎么样?他的最终数组是{10, 3, 2, 5, 4, 1, 6, 7, 8, 9} -
@buraquete 你从哪里得到
{10, 3, 2, 5, 4, 1, 6, 7, 8, 9}?他的最后一个数组是{0, 3, 4, 9, 8, 1, 2, 5, 6, 7}。 0是原始数组中10的索引,3是9的索引,4是8的索引,依此类推。 -
如果
nums[b]非常大并且nums[a]是负数,则此代码Arrays.sort(index, (a, b) -> (nums[b] - nums[a]));可能会失败。整数溢出会抬起丑陋的脑袋。见blog.mischel.com/2016/11/21/…
标签: java algorithm sorting lambda java-8