我正在尝试用Java实现这样的场景。
我有一个ArrayList
["23","5","","","54","20","","","","0"]`
目前,列表未排序,我想以保持空字符串""
的位置的方式对其进行排序。
这意味着空字符串不会被排序,其他值也是如此。 示例 ArrayList的
["0","5","","","20","23","","","","54"].
请注意,之后保留空字符串的位置(最初位于2,3和6,7,8位置),并且仅使用非空值进行排序。我正在使用Java,我真的想要一些想法来开始实现这个要求。我试过谷歌,但无法找到一个良好的开端。
请帮忙,
提前致谢。
答案 0 :(得分:1)
也许是这样的:(致信 Tom 以获得有用的链接)
String[] arr = new String[] { "23","5","","","54","20","","","","0" }; // the original array
boolean[] space = new boolean[arr.length]; // indicates whenever the index contains an empty space
String[] target = new String[arr.length]; // the reslted array
for (int i = 0; i < space.length; i++) // init spaces
{
space[i] = arr[i].isEmpty();
}
Arrays.sort(arr); // sort the original array
int index = 0;
for (int i = 0; i < arr.length; i++)
{
if (arr[i].isEmpty()) continue; // just a space ignore that
index = i; // real values start here
break;
}
for (int i = 0; i < space.length; i++)
{
if (space[i] == true)
{
target[i] = ""; // restore space
}
else
{
target[i] = arr[index]; index++;
}
}
答案 1 :(得分:1)
可能你会想要使用这样的东西:
import java.util.Arrays;
import java.util.LinkedList;
import java.util.TreeSet;
public class StringSort {
public static void main(String[] args) {
String[] numbers = new String[] {"23","5","","","54","20","","","","0"};
// Save the indices to be able to put the sorted numbers back in the array
LinkedList<Integer> indices = new LinkedList<>();
// Keep an ordered list of parsed numbers
TreeSet<Integer> set = new TreeSet<>();
// Skip empty entries, add non-empty to the ordered set and the indices list
for (int i = 0; i < numbers.length; i++) {
if (numbers[i].equals(""))
continue;
set.add(Integer.parseInt(numbers[i]));
indices.add(i);
}
// Put the ordered integers back into the array
for (int i : set) {
numbers[indices.pop()] = Integer.toString(i);
}
System.out.println(Arrays.toString(numbers));
}
}
由于排序,它在O(nlogn)时间运行,但这是可行的。