[LeetCode] Wiggle Sort

简介: Problem Description: Given an unsorted array nums, reorder it in-place such that nums[0] = nums[2] = nums[i - 1]; If i is even, then nums[i] nums[i...

Problem Description:

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

For example, given nums = [3, 5, 2, 1, 6, 4], one possible answer is [1, 6, 2, 5, 3, 4].


The final sorted nums needs to satisfy two conditions:

  1. If i is odd, then nums[i] >= nums[i - 1];
  2. If i is even, then nums[i] <= nums[i - 1].

The code is just to fix the orderings of nums that do not satisfy 1 and 2.

1 class Solution {
2 public: 
3     void wiggleSort(vector<int>& nums) {
4         int n = nums.size();
5         for (int i = 1; i < n; i++)
6             if (((i & 1) && nums[i] < nums[i - 1]) || (!(i & 1) && nums[i] > nums[i - 1]))
7                 swap(nums[i], nums[i - 1]);
8     }
9 };

 

目录
相关文章
LeetCode 376. Wiggle Subsequence
如果连续数字之间的差严格地在正数和负数之间交替,则数字序列称为摆动序列。第一个差(如果存在的话)可能是正数或负数。少于两个元素的序列也是摆动序列。
92 0
LeetCode 376. Wiggle Subsequence
LeetCode 148. Sort List
在 O(n log n) 时间复杂度和常数级空间复杂度下,对链表进行排序。
71 0
LeetCode 148. Sort List
|
索引
LeetCode 75. Sort Colors
给定一个具有红色,白色或蓝色的n个对象的数组,对它们进行就地排序,使相同颜色的对象相邻,颜色顺序为红色,白色和蓝色。 这里,我们将使用整数0,1和2分别表示红色,白色和蓝色。 注意:您不应该使用库的排序功能来解决此问题。
45 0
LeetCode 75. Sort Colors
LeetCode 75 Sort Colors 颜色分类(荷兰国旗)
Given an array with n objects colored red, white or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white and blue. Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.
90 0
|
人工智能 C++ Python
LeetCode 905. Sort Array By Parity
LeetCode 905. Sort Array By Parity
93 0
|
vr&ar
【LeetCode1122】数组的相对排序(哈希or自定义sort)
没错,,简单题,就是说将arr1中有arr2的元素,则按照arr2的元素先排列(特别注意:这里的arr2的元素都是不同的,但是arr1中是可以元素重复的)
176 0
【LeetCode1122】数组的相对排序(哈希or自定义sort)