Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commitdc1b981

Browse files
authored
Create 1968-array-with-elements-not-equal-to-average-of-neighbors.kt
1 parent7fe92db commitdc1b981

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+
classSolution {
5+
funrearrangeArray(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+
classSolution {
27+
funrearrangeArray(nums:IntArray):IntArray {
28+
29+
for (iin1 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)

[8]ページ先頭

©2009-2025 Movatter.jp