【算法】正则序列-美团2021校招笔试

【算法】正则序列-美团2021校招笔试

https://www.nowcoder.com/questionTerminal/0771ab500d424415af6b1aa4c13afcdd?f=discussion


1.题目


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);
        }
    }
    
posted @ 2021-03-11 16:46  musecho  阅读(206)  评论(0编辑  收藏  举报