Skip to content

Commit dc1b981

Browse files
authored
Create 1968-array-with-elements-not-equal-to-average-of-neighbors.kt
1 parent 7fe92db commit dc1b981

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
/*
2+
* O(nlogn) solution (similar to wiggle sort)
3+
*/
4+
class Solution {
5+
fun rearrangeArray(nums: IntArray): IntArray {
6+
nums.sort()
7+
8+
val res = IntArray(nums.size)
9+
var i = 0
10+
var left = 0
11+
var right = nums.lastIndex
12+
13+
while (i < res.size) {
14+
res[i++] = nums[left++]
15+
if (left <= right)
16+
res[i++] = nums[right--]
17+
}
18+
19+
return res
20+
}
21+
}
22+
23+
/*
24+
* O(n) solution, check for any increasing/decreasing subarrays at i - i to i + 1, if found i with i + 1 to remove the increasing/decreasing subarray
25+
*/
26+
class Solution {
27+
fun rearrangeArray(nums: IntArray): IntArray {
28+
29+
for (i in 1 until nums.lastIndex) {
30+
if (nums[i - 1] < nums[i] && nums[i] < nums[i + 1] ||
31+
nums[i - 1] > nums[i] && nums[i] > nums[i + 1])
32+
nums[i] = nums[i + 1].also { nums[i + 1] = nums[i] }
33+
}
34+
35+
return nums
36+
}
37+
}

0 commit comments

Comments
 (0)