当前位置:网站首页>LeetCode 每日一题——324. 摆动排序 II
LeetCode 每日一题——324. 摆动排序 II
2022-06-29 02:47:00 【SK_Jaco】
1.题目描述
给你一个整数数组 nums,将它重新排列成 nums[0] < nums[1] > nums[2] < nums[3]… 的顺序。
你可以假设所有输入数组都可以得到满足题目要求的结果。
示例 1:
输入:nums = [1,5,1,1,6,4]
输出:[1,6,1,5,1,4]
解释:[1,4,1,5,1,6] 同样是符合题目要求的结果,可以被判题程序接受。
示例 2:
输入:nums = [1,3,2,2,3,1]
输出:[2,3,1,3,1,2]
2.解题思路与代码
2.1 解题思路
这道题需要将原数组排列成 nums[0] < nums[1] > nums[2] < nums[3] 这样一大一小的结构,那么我们可以将数组进行按照从小到大排序,并从中间切分,左边部分是较小的,右边部分是较大,然后按照一小一大的顺序依次放回数组,便能够得到结果。以数组 nums = [1,5,1,1,6,4] 为例
使用 left 指向较小部分最右侧,right 指向较大部分左右侧,用 getSmaller 来决定是选择较小部分还是较大部分的数

2.2 代码
class Solution {
public void wiggleSort(int[] nums) {
// 使用一个临时数组暂存
int[] tmp = new int[nums.length];
for (int i = 0; i < nums.length; i++) {
tmp[i] = nums[i];
}
// 对数组进行排序
Arrays.sort(tmp);
// left 从较小区域的最右侧开始
int left = (nums.length - 1) >> 1;
// right 从较大区域的最右侧开始
int right = nums.length - 1;
// 是否选择较小区域
boolean getSmaller = true;
for (int i = 0; i < nums.length; i++) {
if (getSmaller) {
// 选择较小区域,left 左移一位,并 getSmaller 变为false 下次取较大区域
nums[i] = tmp[left--];
getSmaller = false;
} else {
// 选择较大区域,right 左移一位,并 getSmaller 变为true 下次取较小区域
nums[i] = tmp[right--];
getSmaller = true;
}
}
}
}
2.3 测试结果
通过测试

3.总结
- 首先对数组进行排序,然后对半分成较小数区域和较大数区域
- 使用双指针来对较小区域和较大区域进行选择并放入数组中
边栏推荐
- arraylist基操和添加元素源码
- Relationship between EMC, EMI and EMS
- Mipi d-phy -- contents of HS and LP agreements
- Apache does not parse PHP files, but directly displays the source code
- PWN攻防世界guess_num
- Kubernetes: container resource requirements and constraints (constraints)
- Table implements alternative adaptation through pseudo classes
- There is a time delay for the click event on the mobile terminal. What is the delay time? How to solve it?
- Exec function of PHP
- [线性代数] 1.2 全排列和对换
猜你喜欢

What is a thread pool?

sql训练01

Have you learned the common SQL interview questions on the short video platform?

SQL training 01

PWN攻防世界Level2

PWN attack and defense world level2
![[Algèbre linéaire] 1.1 déterminant du deuxième et du troisième ordre](/img/ea/70b59c64d3287a887e371a9181fe45.png)
[Algèbre linéaire] 1.1 déterminant du deuxième et du troisième ordre

EMC、EMI、EMS的關系

Has Moore's law come to an end?

学习太极创客 — MQTT 第二章(九)本章测试
随机推荐
解决allegro中测量距离时,点击一个点后光标闪烁的问题
PMP项目管理概述
mark
How to add the live video function to the website built by your own live video software (build a live video website)
认证培训|StreamNative Certification 培训第2期
手机开户股票开户安全吗?开户很难么?
18. ` BS object. Nom du noeud. Suivant Sibling ` get Brother Node
Redis master-slave replication
String substitution
Method overload summary
2022年启牛学堂证券开户安全的嘛?
table通过伪类实现 另类自适应
Relationship between EMC, EMI and EMS
Introduction to openresty
Application of fsockopen function
allegro对走好的线取消走线的方法
PWN attack and defense world level2
正则表达式(?:pattern)
Use photoshop2022 to create a wonderful gradient effect for pictures
Kubernetes: container resource requirements and constraints (constraints)