import java.util.Scanner; import java.util.*; public class Main{ public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int[] nums = new int[n+1]; boolean[] visted = new boolean[n+1]; int VISITED = 10001; for(int i=1;i<=n;i++) nums[i] = sc.nextInt(); Arrays.sort(nums,1,n); for(int i=1;i<=n;i++){ if(nums[i]<=n && nums[i]>=1 && !visted[nums[i]] ) { visted[nums[i]] = true; nums[i] = VISITED; } } int res = 0; for(int i=1,j=1;i<=n;i++){ if(!visted[i]){ while(nums[j]==VISITED) j++; res += Math.abs(nums[j]-i); nums[j] = VISITED; } } System.out.println(res); } }
这样 最后一个样例通不过 应该是在数组上面出问题了
不使用 n+1 的数组 就可以全部通过
import java.util.Scanner; import java.util.*; public class Main{ public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int[] nums = new int[n]; for(int i=0;i<n;i++) nums[i] = sc.nextInt(); Arrays.sort(nums); int res = 0; for(int i=1;i<=n;i++){ res += Math.abs(nums[i-1]-i); } System.out.println(res); } }