File tree Expand file tree Collapse file tree 2 files changed +39
-0
lines changed Expand file tree Collapse file tree 2 files changed +39
-0
lines changed Original file line number Diff line number Diff line change 440
440
552|[ Student Attendance Record II] ( ./0552-student-attendance-record-ii.js ) |Hard|
441
441
553|[ Optimal Division] ( ./0553-optimal-division.js ) |Medium|
442
442
554|[ Brick Wall] ( ./0554-brick-wall.js ) |Medium|
443
+ 556|[ Next Greater Element III] ( ./0556-next-greater-element-iii.js ) |Medium|
443
444
557|[ Reverse Words in a String III] ( ./0557-reverse-words-in-a-string-iii.js ) |Easy|
444
445
560|[ Subarray Sum Equals K] ( ./0560-subarray-sum-equals-k.js ) |Medium|
445
446
563|[ Binary Tree Tilt] ( ./0563-binary-tree-tilt.js ) |Easy|
Original file line number Diff line number Diff line change
1
+ /**
2
+ * 556. Next Greater Element III
3
+ * https://leetcode.com/problems/next-greater-element-iii/
4
+ * Difficulty: Medium
5
+ *
6
+ * Given a positive integer n, find the smallest integer which has exactly the same digits existing
7
+ * in the integer n and is greater in value than n. If no such positive integer exists, return -1.
8
+ *
9
+ * Note that the returned integer should fit in 32-bit integer, if there is a valid answer but it
10
+ * does not fit in 32-bit integer, return -1.
11
+ */
12
+
13
+ /**
14
+ * @param {number } n
15
+ * @return {number }
16
+ */
17
+ var nextGreaterElement = function ( n ) {
18
+ const digits = [ ...String ( n ) ] ;
19
+ let i = digits . length - 2 ;
20
+
21
+ while ( i >= 0 && digits [ i ] >= digits [ i + 1 ] ) i -- ;
22
+ if ( i < 0 ) return - 1 ;
23
+
24
+ let j = digits . length - 1 ;
25
+ while ( j >= 0 && digits [ j ] <= digits [ i ] ) j -- ;
26
+
27
+ [ digits [ i ] , digits [ j ] ] = [ digits [ j ] , digits [ i ] ] ;
28
+ let left = i + 1 ;
29
+ let right = digits . length - 1 ;
30
+ while ( left < right ) {
31
+ [ digits [ left ] , digits [ right ] ] = [ digits [ right ] , digits [ left ] ] ;
32
+ left ++ ;
33
+ right -- ;
34
+ }
35
+
36
+ const result = + digits . join ( '' ) ;
37
+ return result > n && result <= 2 ** 31 - 1 ? result : - 1 ;
38
+ } ;
You can’t perform that action at this time.
0 commit comments