Java版本:先将数组排序,从中间将排好序的数组分为small部分和large部分。

每次从小区间找一个值插入偶数位,从大区间找一个值插入奇数位。

 public void wiggleSort(int[] nums) {
int[] temp = Arrays.copyOfRange(nums, , nums.length);
Arrays.sort(temp);
//中间点,左侧都是小值
int small = temp.length / + (temp.length % == ? - : );
//右侧都是大值
int large = temp.length - ;
for (int i = , j = ; i < temp.length; i += , j += ) {
if (j < temp.length) {
//用大值插入odd位置
nums[j] = temp[large--];
}
//用小值插入even位置
nums[i] = temp[small--];
}
}

补充一个python的版本:

 class Solution:
def wiggleSort(self, nums: 'List[int]') -> None:
temp = sorted(nums)
n = len(nums)
mid = n // 2 + n % 2
p1 = temp[:mid]
p2 = temp[mid:]
i =
j =
k =
while k < n:
if k % == :
temp[k] = p1[i]
k +=
i +=
else:
temp[k] = p2[j]
k +=
j +=
print(temp)
for i in range(,n):
if temp[i-] == temp[i]:
nums.clear()
nums.extend(temp[i:])
nums.extend(temp[:i])
print(nums)
return
nums.clear()
nums.extend(temp)

leetcode324的更多相关文章

  1. [Swift]LeetCode324. 摆动排序 II | Wiggle Sort II

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

  2. leetcode324 摆动排序II

      1. 首先考虑排序后交替插入 首尾交替插入,这种方法对于有重复数字的数组不可行: class Solution { public: void wiggleSort(vector<int> ...

  3. leetcode探索高级算法

    C++版 数组和字符串 正文 链表: 正文 树与图: 树: leetcode236. 二叉树的最近公共祖先 递归(先序) leetcode124二叉树最大路径和 递归 图: leetcode 547朋 ...

随机推荐

  1. ==,equals,hashcode

    总结:== 基本类型比较值,引用类型比较是不是同一个对象,也就是比较内存地址 equals 在没有覆盖的情况下是比较 引用的地址的  和 == 一样 hashcode 和equals关系: hashc ...

  2. 纯CSS绘制三角形(各种角度)类似于使用字符画法,根据位移不同,也可以使用两个元素画出三角边框

    我们的网页因为 CSS 而呈现千变万化的风格.这一看似简单的样式语言在使用中非常灵活,只要你发挥创意就能实现很多比人想象不到的效果.特别是随着 CSS3 的广泛使用,更多新奇的 CSS 作品涌现出来. ...

  3. JavaWeb学习总结(二)-修改Tomcat服务器的端口(半年之后再总结)

    一.Tomcat服务器端口的配置 Tomcat的所有配置都放在conf文件夹之中,里面的server.xml文件是配置的核心文件(hibernate.cfg.xml是核心配置文件). 如果想修改Tom ...

  4. 初学者必读之AJAX简单实例2

    1.a前台页面的主体 b.添加script函数: 这个函数功能1:把文本框的数据传入到后台程序   2.再接收后台程序处理之后的数据,将其插入到页面 2.后台程序功能 软件测试

  5. 一 JAVA整体概念以及安装部署

    JAVA 基本概念  JVM(JAVA virtual machine)java虚拟机,是java的能跨平台的核心,java的跨平台实现,就是在各种系统中布置JVM,然后java应用运行在JVM中,相 ...

  6. SQLServer2008开启远程连接

    1.查看sqlserver brower协议是否启动 2.对象资源管理器 右键属性->选择-> 方面->服务器配置->Remoteaccess ->True 3.对象资源 ...

  7. 【python】网络编程-UDP协议套接字

    服务器端: #!/usr/bin/env python from socket import * from time import ctime HOST = '' PORT = 21567 BUFSI ...

  8. win xp 关闭动画屏幕角色,那只小狗

    这个动画屏幕角色每次会占用两秒左右的时间. 在搜索选项中打开"改变首选项(G)" -选择 “不使用动画屏幕角色(S)”. - -

  9. 阿里云服务器挖矿wipefs处理

    查看指定日志修改过的文件:  [root@iZbp12v0moqn078lm0t0l5Z 2018-04-26]# find /data/www/manage -ctime 0 -exec ls -l ...

  10. 学习笔记之.NET Core

    source code https://github.com/haotang923/dotnet/tree/master/src .NET Documentation | Microsoft Docs ...