Skip to content

Commit b0e2c30

Browse files
committed
feat: complete No.1053
1 parent 205925f commit b0e2c30

File tree

1 file changed

+65
-2
lines changed

1 file changed

+65
-2
lines changed

1001-1100/1053. Previous Permutation With One Swap.md

+65-2
Original file line numberDiff line numberDiff line change
@@ -49,14 +49,77 @@ Explanation: Swapping 9 and 7.
4949
## Solution
5050

5151
```javascript
52+
/**
53+
* @param {number[]} arr
54+
* @return {number[]}
55+
*/
56+
var prevPermOpt1 = function(arr) {
57+
for (var i = arr.length - 2; i >= 0; i--) {
58+
if (arr[i] <= arr[i + 1]) continue;
59+
var max = 0;
60+
var maxIndex = -1;
61+
for (var j = i + 1; j < arr.length; j++) {
62+
if (arr[j] > max && arr[j] < arr[i]) {
63+
max = arr[j];
64+
maxIndex = j;
65+
}
66+
}
67+
swap(arr, i, maxIndex);
68+
break;
69+
}
70+
return arr;
71+
};
72+
73+
var swap = function(arr, i, j) {
74+
var tmp = arr[i];
75+
arr[i] = arr[j];
76+
arr[j] = tmp;
77+
};
78+
```
79+
80+
**Explain:**
81+
82+
1. we need a smaller array than the current one, so that we need to swap a smaller number from right to left
83+
2. we need a largest array from all the possible result, so that we are going to find the first possible index to swap, from the right of array
84+
3. from right find a possible index to swap, find biggest number smaller than this one to swap on the right
85+
86+
**Complexity:**
87+
88+
* Time complexity : O(n).
89+
* Space complexity : O(1).
5290

91+
## Solution 2
92+
93+
```javascript
94+
/**
95+
* @param {number[]} arr
96+
* @return {number[]}
97+
*/
98+
var prevPermOpt1 = function(arr) {
99+
for (var i = arr.length - 2; i >= 0; i--) {
100+
if (arr[i] <= arr[i + 1]) continue;
101+
for (var j = arr.length; j > i; j--) {
102+
if (arr[j] < arr[i] && arr[j] !== arr[j - 1]) {
103+
swap(arr, i, j);
104+
return arr;
105+
}
106+
}
107+
}
108+
return arr;
109+
};
110+
111+
var swap = function(arr, i, j) {
112+
var tmp = arr[i];
113+
arr[i] = arr[j];
114+
arr[j] = tmp;
115+
};
53116
```
54117

55118
**Explain:**
56119

57-
nope.
120+
because we know that numbers from right to left is in order, (from solution 1), we can just find the first one from right.
58121

59122
**Complexity:**
60123

61124
* Time complexity : O(n).
62-
* Space complexity : O(n).
125+
* Space complexity : O(1).

0 commit comments

Comments
 (0)