给定一个无序的数组 nums,将它重新排列成 nums[0] < nums[1] > nums[2] < nums[3]… 的顺序。要求时间复杂度是O(N)。
示例:
输入: nums = [1, 5, 1, 1, 6, 4]
输出: 一个可能的答案是 [1, 4, 1, 5, 1, 6]
注:此处并没有满足时间复杂度的要求
思路
- 找到中位数即可,即中位数的左边为较小值,中位数的右边为较大值,见有大神用最大堆最小堆做的,不太懂,求指点
- 取数组长度的大的那一半
- 将小的那一半插空到大的那一半里
public static void main(String[] args){
int[] nums = {1,5,1,1,4,6,3};
List min = new ArrayList();
List max = new ArrayList();
for (int i=0; i<nums.length; i++){
int index = nums[i];
for (int j=0; j<nums.length; j++){
if (nums[j]>index){
max.add(nums[j]);
}else {
min.add(nums[j]);
}
}
if (max!=null && min!=null && max.size()==nums.len