Java leetcode 上涉及反向排序数组(如 3,2,1)的测试用例下一个整数数组排列失败的解决方案
Java solution for next integer array permutation fails incase of a testcase involving reverse sorted array like 3,2,1 on leetcode
力扣题:https://leetcode.com/problems/next-permutation/
当输入按降序排列(如 3,2,1)时,代码会失败,即使我已经提供了该条件的具体情况。我做错了什么?
class Solution {
public void nextPermutation(int[] nums) {
int temp = 0, a, b = -1;
for (int i = nums.length - 1; i >= 1; i--) {
if (nums[i] > nums[i - 1]) {
temp = nums[i - 1];
b = i - 1;
break;
}
}
//attempting to reverse array
if (b == -1) {
for (int s = 0; s < nums.length - 1; s++) {
nums[s] = nums[s] * -1;
}
Arrays.sort(nums);
for (int s = 0; s < nums.length - 1; s++) {
nums[s] = nums[s] * -1;
}
} else {
for (int i = nums.length - 1; i >= 1; i--) {
if (nums[i] > temp) {
a = nums[i];
nums[i] = temp;
nums[b] = a;
Arrays.sort(nums, b, nums.length - 1);
break;
}
}
}
}
}
我的想法灵感来自:https://www.youtube.com/watch?v=LuLCLgMElus&list=PLgUwDviBIf0rPG3Ictpu74YWBQ1CaBkm2&index=10
如果您特别担心数组按降序排序的情况,那么您对数组所做的修改是错误的。
对于这种情况,您需要 reverse
数组或简单地按 increasing
顺序对数组进行排序。
但是你错误地反转了数组。
例如:[4,3,2,1]
=> [-4,-3,-2,-1] (乘以 -1) => [-4,-3,-2, -1] (排序(已经排序)) => [4,3,2,1] (乘以-1)。
因此,数组永远不会反转。
因此,只需使用 Arrays.sort(nums)
即可获得所需的结果。
力扣题:https://leetcode.com/problems/next-permutation/
当输入按降序排列(如 3,2,1)时,代码会失败,即使我已经提供了该条件的具体情况。我做错了什么?
class Solution {
public void nextPermutation(int[] nums) {
int temp = 0, a, b = -1;
for (int i = nums.length - 1; i >= 1; i--) {
if (nums[i] > nums[i - 1]) {
temp = nums[i - 1];
b = i - 1;
break;
}
}
//attempting to reverse array
if (b == -1) {
for (int s = 0; s < nums.length - 1; s++) {
nums[s] = nums[s] * -1;
}
Arrays.sort(nums);
for (int s = 0; s < nums.length - 1; s++) {
nums[s] = nums[s] * -1;
}
} else {
for (int i = nums.length - 1; i >= 1; i--) {
if (nums[i] > temp) {
a = nums[i];
nums[i] = temp;
nums[b] = a;
Arrays.sort(nums, b, nums.length - 1);
break;
}
}
}
}
}
我的想法灵感来自:https://www.youtube.com/watch?v=LuLCLgMElus&list=PLgUwDviBIf0rPG3Ictpu74YWBQ1CaBkm2&index=10
如果您特别担心数组按降序排序的情况,那么您对数组所做的修改是错误的。
对于这种情况,您需要 reverse
数组或简单地按 increasing
顺序对数组进行排序。
但是你错误地反转了数组。
例如:[4,3,2,1]
=> [-4,-3,-2,-1] (乘以 -1) => [-4,-3,-2, -1] (排序(已经排序)) => [4,3,2,1] (乘以-1)。
因此,数组永远不会反转。
因此,只需使用 Arrays.sort(nums)
即可获得所需的结果。