输入包括两行,第一行一个整数n(1 ≤ n ≤ 50),即序列的长度 第二行n个整数x[i](1 ≤ x[i] ≤ 100),即序列中的每个数
输出一个整数,即最少需要移动的元素个数
3 3 2 1
2
import java.util.Arrays; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int[] arr = new int[n]; int[] arrSorted = new int[n]; int count = 0; for (int i = 0; i < n; i++) { int cur = sc.nextInt(); arr[i] = cur; arrSorted[i] = cur; } Arrays.sort(arrSorted); for (int i = 0; i < n; i++) { if (arr[i] != arrSorted[i]) { count++; } } System.out.println(count); } }
#include<iostream> #include<algorithm> using namespace std; int main(){ int n,count=0; cin>>n; int* a=new int[n]; int* origin=new int[n]; for(int i=0;i<n;i++){ cin>>a[i]; origin[i]=a[i]; } sort(a,a+n); for(int i=0;i<n;i++){ if(origin[i]!=a[i]) count++; } cout<<count<<endl; }
#include <bits/stdc++.h> using namespace std; bool cmp(int a, int b){ return a<b; } int main() { int n; while(cin>>n){ int a[n],b[n],cnt=0; for(int i=0;i<n;i++){ cin>>a[i]; b[i] = a[i]; } sort(a,a+n,cmp); for(int i=0;i<n;i++) if(a[i]!=b[i]) cnt++; cout<<cnt<<endl; } return 0; }
import java.util.*; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); ArrayList arr = new ArrayList(); for (int i=0; i!=n; i++) { arr.add(sc.nextInt()); } ArrayList sortArr = new ArrayList(arr); Collections.sort(sortArr); int count = 0; for (int i=0; i!=n; i++) { if (!sortArr.get(i).equals(arr.get(i))) { count++; } } System.out.println(count); } }
n = eval(input()) a = list(map(int,input().split())) b = sorted(a) count = 0 for i in range(n): if a[i] != b[i]: count += 1 print(count)
//题目说的不是很清楚,想问的是几个位置的数字变化
#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
int main()
{
int num, x;
cin >> num;
vector<int> nums, temp;
while (num--)
{
cin >> x;
nums.push_back(x);
temp.push_back(x);
}
sort(nums.begin(), nums.end());
int cnt = 0;
for (int i = 0; i < nums.size(); i++)
{
if (nums[i] != temp[i])
cnt++;
}
cout << cnt << endl;
return 0;
}
const readline=require('readline');//借助node.js进行在线笔试的输入输出 const rl=readline.createInterface({ input:process.stdin, output:process.stdout }); var rows=[]; rl.on("line",function(line){ rows.push(line);//将每次输入的行数据存入 if(2==rows.length){ var num=rows[0]; var s=rows[1]; var arr=s.split(" "); var arr1=s.split(" "); arr.sort(function(a,b){//数组排序 return a-b; }); var sum=0; for (var i=0;i<num;i++){ if(arr1[i]!=arr[i]){ sum++; } }//end for console.log(sum); rows.length=0;//状态重置 }//end if });多行输入参考:https://segmentfault.com/a/1190000010715910