你希望改最少的数,使得这个序列满足a[i+1]-a[i]=i吗?
题目链接:https://ac.nowcoder.com/acm/contest/7780/B
import java.util.*; public class Main{ public static void main(String[] args) { Scanner sc = new Scanner(System.in); HashMap<Long,Integer> map = new HashMap<>(); int n = sc.nextInt(); long[] a = new long[n+1]; for(int i = 1 ;i <= n ; i++){ a[i] = a[i-1]+i-1; } int count = 1; for(int i = 1;i <= n;i++){ int num = sc.nextInt(); if(!map.containsKey(num - a[i])){ map.put(num - a[i],1); }else{ map.put(num - a[i],map.get(num - a[i]) + 1); } count = Math.max(count,map.get(num - a[i])); } System.out.println(n - count); } }
依然是需要用到hashmap,经过几次的使用借鉴,对hashmap的函数方法已经有一定的了解,已经不用去百度了,这是自己的进步,表扬一下。在这提中,没有想到,直接利用公式输出的数组,和例子给出的数组室友规律的,也就是说,公式输出的数组和自己输入的数组之间,对应位置的元素相减得到的差值是相同的,也就有了if语句的判断,是否存在这一个键,如果不存在则重新开一个键,如果存在,那么这个键的对应值就加一。之前那一个不一样的键导致整个数组下来,hash表中对应值少了1.那么直接用整个输入的数n减去计数词count就可以得到出错的数字的个数。这里count用比较最大法,不断增加。