A
A
Algorithm Practice
Search…
A
A
Algorithm Practice
Introduction
Lintcode
Leetcode
Math
Tree
Graph
Two Pointers
Linked List
Topological Sort
Hash Table
Trie
Sort
49 Group Anagrams
75 Sort Colors
164 Maximum Gap
179 Largest Number
274 H-Index
280 Wiggle Sort
296 Best Meeting Point
315 Count of Smaller Numbers After Self
324 Wiggle Sort II
327 Count of Range Sum
406 Queue Reconstruction by Height
462 Minimum Moves to Equal Array Elements II
493 Reverse Pairs
Binary Search
Heap
Breadth First Search
Stack
Backtracking
Dynamic Programming
Union Find
Scan Line
String
Reservoir Sampling
Recursion
Google
Powered By
GitBook
280 Wiggle Sort
280.
Wiggle Sort
1. Question
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]
.
2. Implementation
1
class
Solution
{
2
public
void
wiggleSort
(
int
[]
nums
)
{
3
for
(
int
i
=
0
;
i
<
nums
.
length
-
1
;
i
++
)
{
4
if
(
i
%
2
==
0
&&
nums
[
i
]
>
nums
[
i
+
1
]
||
5
i
%
2
==
1
&&
nums
[
i
]
<
nums
[
i
+
1
])
{
6
swap
(
nums
,
i
,
i
+
1
);
7
}
8
}
9
}
10
11
public
void
swap
(
int
[]
nums
,
int
i
,
int
j
)
{
12
int
temp
=
nums
[
i
];
13
nums
[
i
]
=
nums
[
j
];
14
nums
[
j
]
=
temp
;
15
}
16
}
Copied!
3. Time & Space Complexity
时间复杂度O(n), 空间复杂度O(1)
Previous
274 H-Index
Next
296 Best Meeting Point
Last modified
2yr ago
Copy link
Contents
280. Wiggle Sort
1. Question
2. Implementation
3. Time & Space Complexity