【算法】正则序列-美团2021校招笔试
https://www.nowcoder.com/questionTerminal/0771ab500d424415af6b1aa4c13afcdd?f=discussion
1.题目
![](https://i-blog.csdnimg.cn/blog_migrate/7794bcef5a05e5b63d62a5dafb5f216a.png)
![](https://i-blog.csdnimg.cn/blog_migrate/19a58eeaf65faa3de3b40662049b4fef.png)
2.我的解法
-
代码
package 正则序列; import java.util.Arrays; import java.util.Scanner; /* 使得调整次数最少, 先从小到大排序, 再依次调整为1-n */ public class RegularSequence { public int regularSequence(int num, int[] sequence, int rs) { Arrays.sort(sequence);//排序 int nowIndex = 1;//需要调整为的结果 for (int i = 0; i < sequence.length; i++) { rs += Math.abs(nowIndex - sequence[i]); nowIndex++; } return rs; } public static void main(String[] args) { RegularSequence regularSequence = new RegularSequence(); Scanner scanner = new Scanner(System.in); int num = scanner.nextInt(); int[] sequence = new int[num]; for (int i = 0; i < sequence.length; i++) { sequence[i] = scanner.nextInt(); } int rs = 0; rs = regularSequence.regularSequence(num, sequence, rs); System.out.println(rs); } }