Skip to content

Commit f31f1ce

Browse files
author
ongch
committed
refactor: swap function
1 parent d611090 commit f31f1ce

File tree

1 file changed

+8
-6
lines changed

1 file changed

+8
-6
lines changed

LeetcodeProblems/Algorithms/Next_Permutation.js

+8-6
Original file line numberDiff line numberDiff line change
@@ -45,21 +45,23 @@ Output: [1,5,1]
4545

4646
for (let l = nums.length - 1; l > k; l--) {
4747
if (nums[l] > nums[k]) {
48-
let temp = nums[k];
49-
nums[k] = nums[l];
50-
nums[l] = temp;
48+
swap(nums, k, l);
5149
break;
5250
}
5351
}
5452

5553
reverse(nums, k + 1, nums.length -1);
5654
};
5755

56+
function swap(arr, a, b) {
57+
let temp = arr[a];
58+
arr[a] = arr[b];
59+
arr[b] = temp;
60+
}
61+
5862
function reverse(nums, start ,end) {
5963
while(start < end) {
60-
let temp = nums[start];
61-
nums[start] = nums[end];
62-
nums[end] = temp;
64+
swap(nums, start, end);
6365
start++;
6466
end--;
6567
}

0 commit comments

Comments
 (0)