众所周知的问题:
给定 n 个范围从 1 到 n 的数组。就地排序 O(1) 空间。
Input: [3, 1, 5, 4, 2]
Output: [1, 2, 3, 4, 5]
我的解决方案是
public static void sort(int[] nums) {
int n = nums.length;
for(int i = 0; i < n; i++){
if(nums[nums[i] -1] != nums[i]){ // if I use while here it works.
int j = nums[i] -1;
int temp = nums[j];
nums[j] = nums[i];
nums[i] = temp;
}
}
}
但这有一个错误如下。
Input: [1, 5, 6, 4, 3, 2]
Wrong output: [1, 3, 2, 4, 5, 6]
如果我在 for 循环中使用 while
(而不是 if
),它就可以工作。
我不明白为什么如果我在 for
循环中使用 if
语句,它会出现错误。
有人可以解释一下原因吗?
最佳答案
如果你不想这样做Arrays.sort(nums)
int[] nums= new int[]{ 1, 5, 6, 4, 3, 2 };
int n = nums.length;
for (int i = 0; i < nums.length; i++) {
for (int j = 0; j < nums.length; j++) {
if (nums[i] < nums[j]) {
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
}
}
for (int i = 0; i < n; i++){
System.out.println(nums[i]);
}
输出
[1, 2, 3, 4, 5, 6]
关于java - 为什么这个循环排序实现有一个错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59649935/