版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_32767041/article/details/86495544
Description
牛客网 2018校招真题 排序
Solving Ideas
将数组排序与原数组进行比较,统计出现对应位置数字不同的次数,即为需要移动的最少次数。
因为当一个元素不在它原来所在的位置,这个元素就是被移动了的,如原序列[3, 1],排序后变为[1, 3],需要移动两次,将1往前移,将3往后移(一次移动的步长无限制)。
Time complexity :
Space complexity :
Solution
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
int[] x = new int[n], y = new int[n];
String[] strs = br.readLine().split(" ");
for (int i = 0; i < n; i++) {
x[i] = Integer.parseInt(strs[i]);
y[i] = x[i];
}
Arrays.sort(y);
int count = 0;
for (int i = 0; i < n; i++) {
if (x[i] != y[i]) count++;
}
System.out.println(count);
}
}