Wiggle Sort II

来源:互联网 发布:疾病自测软件 编辑:程序博客网 时间:2024/05/01 00:54

Given an unsorted array nums, reorder it such that nums[0] < nums[1] > nums[2] < nums[3]….

Example:
(1) Given nums = [1, 5, 1, 1, 6, 4], one possible answer is [1, 4, 1, 5, 1, 6].
(2) Given nums = [1, 3, 2, 2, 3, 1], one possible answer is [2, 3, 1, 3, 1, 2].

Note:
You may assume all input has valid answer.

Follow Up:
Can you do it in O(n) time and/or in-place with O(1) extra space?

  • 解答1:(1)首先利用计数排序算法,将数组排序,并统计小于等于nums[index]的数的总个数;
  • (2)寻找数组中位数,从中位数出发,小于中位数的置于nums数组中index为偶数的位置,大于中位数的置于nums数组中index为奇数的位置处;
  • (3)示例如下:数组[1,4,3,6,9,2,4,4,3,1]->
    count{
    1:2,
    4:3,
    3:2,
    6:1,
    9:1,
    2:1
    }
    totalCount{
    1:2,
    2:3,
    3:5,
    4:8,
    5:8,
    6:9,
    7:9,
    8:9,
    9:10
    }
    计算中位数为3,由3依次向小端(3,2,1)取,置于nums数组奇数小标处;由3依次向上取(4,6,9)置于nums数组偶数小标处。
 var wiggleSort = function(nums){    //本题仍然采用计数排序算法    var N=nums.length,  //记录nums数据长度        i=0,        curr,        max=0,        sortNums=[],        count={},        totalCount={};    var middle=Math.ceil(N/2);  //记录数组中间位置    // if(N===0||N===1)   //为空数组或者只有一个元素时返回    // {    // }    while(i<N)  //统计nums数组中每个值对应的数据数目    {        curr=nums[i];        if(curr>max)//遍历数组的同时顺便求出最大值        {            max=curr;        }        if(count.hasOwnProperty(curr))//将数组中的数值放进count对象中        {            count[curr]++;        }else{            count[curr]=1;        }        i++;    }    //统计0-max中比自身小的数目    if(count[0])    {         totalCount[0]=count[0];    }else{        totalCount[0]=0;     }    for(var k=1;k<=max;k++)    {        if(count[k])        {            totalCount[k]=count[k]+totalCount[k-1];        }else{            totalCount[k]=totalCount[k-1];        }    }    //将nums由大到小依次排列放置于sortNums    for(var key in count)    {        while(count[key])        {            totalCount[key]--;//sortNums数组从0开始存储,所以插入的位置首先减一            sortNums[totalCount[key]]=key;            count[key]--;    //每在sortNums数组中插入一个元素,则count中数量减一        }    }    //从sortNums中间位置向两边依次插入nums中    for(var index=0;index<N;index++)    {        if(index%2===0)        {        nums[index]=parseInt(sortNums[middle-1-Math.ceil(index/2)]);//偶数位置放置小数据        }else{        nums[index]=parseInt(sortNums[N-Math.ceil(index/2)]);        }    }};`这里写代码片`

思路2:是网上一个经典的算法,小的自叹不如!!!
就此附上链接供大家参考:https://leetcode.com/discuss/77133/o-n-o-1-after-median-virtual-indexing

0 0
原创粉丝点击