-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path556_NextGreaterElement3.swift
44 lines (41 loc) · 1.06 KB
/
556_NextGreaterElement3.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
class Solution {
func nextGreaterElement(_ n: Int) -> Int {
if n <= 10 {
return -1
}
var num = n
var digits = [Int]()
var maxDigit = -1
var lastDigit = -1
while num > 0 {
let digit = num % 10
lastDigit = digit
num = num / 10
digits.append(digit)
if digit >= maxDigit {
maxDigit = digit
} else {
break
}
}
digits = digits.sorted()
var index = 0
while index < digits.count && digits[index] <= lastDigit{
index += 1
}
if index == digits.count {
return -1
}
var tail = digits[index]
for i in 0..<digits.count {
num = num * 10
if i == index {
continue
} else {
tail = tail * 10 + digits[i]
}
}
let result = num+tail
return result > n && result <= Int32.max ? result : -1
}
}