leetcode:324. 摆动排序 II

leetcode:969. 煎饼排序

在这里插入图片描述
思路

  1. 将给定数组排序并逆序;
  2. 拆分处理后的数组,得到两个数组;
  3. 将一个数组插入至另一个数组。
[4,6,5,5]
1. 排序、逆序		==>	[6,5,5,4]
2. 拆分			==>	[6,5] & [5,4]
3. 合并			==>	[5, ,4, ]
					[ ,6, ,5]
4. result		==>	[5,6,4,5]
def resolution(nums):
    length = len(nums)
    if(length == 0 or length == 1):
        return nums
    nums.sort(reverse=True)
    nums_1, nums_2 = [], []
    # round函数(四舍五入):将4.5 => 4, 将4.51 => 5
    for i in range(round((length/2)-0.1)):
        nums_1.append(nums.pop(0))
    nums_2 = nums.copy()
    count = 1
    while(nums_1):
        nums_2.insert(count, nums_1.pop(0))
        count += 2
    nums = nums_2
    return nums
if __name__ == "__main__":
    nums = [1,1,2,2,2,2,1,1,1]	# ==> [1, 2, 1, 2, 1, 2, 1, 2, 1]
    # nums = [4,5,5,6]			  ==> [5, 6, 4, 5]
    # nums = [2,1]				  ==> [1,2]
    res = resolution(nums)
    print(res)
function sort_fun(prev, curr){
    if(prev > curr){return -1}
    else if(prev < curr){return 1}
    else{return 0}
}
function resolution(nums){
    let length = nums.length;
    if(length == 0 || length == 1){return nums}
    nums.sort(sort_fun);
    length /= 2;
    length = length.toFixed(0);
    if(length * 2 != nums.length){length -= 1}
    let nums_1 = nums.slice(0, length);
    let nums_2 = nums.slice(length, nums.length);
    let res = [], count = 0;
    while(true){
        if(count < nums_2.length){
            res.push(nums_2[count]);
        }
        if(count < nums_1.length){
            res.push(nums_1[count]);
        }
        if(count > nums_1.length && count > nums_2.length){
            return res
        }
        count += 1;
    }
}
let obj = [1,2,1,2,2,2,1,1,1];	// ==> (9) [1, 2, 1, 2, 1, 2, 1, 2, 1]
//	obj = [2,1]					   ==> (2) [1, 2]
//	obj = [4,5,5,6]				   ==> (4) [5, 6, 4, 5]
//	obj = [1,5,1,1,6,4]			   ==> (6) [1, 6, 1, 5, 1, 4]
let res = resolution(obj);
console.info(res);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值