欢迎访问我的CCF认证解题目录
题目描述
思路过程
n最大值为1000,一看就想直接暴力解法,两重for循环,一个一个判断就可以了,时间复杂度为O()
O(
)代码
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int[] number = new int[n];
int count = 0;
for ( int i = 0; i < number.length; i++ ) {
number[i] = in.nextInt();
}
for ( int i = 0; i < number.length; i++ ) {
for ( int j = i+1; j < number.length; j++ ) {
if ( Math.abs((int)(number[i]-number[j]))== 1 ) {//差值为1
count++;
}
}
}
System.out.println(count);
}
}
我们也可以定义一个数组存储出现的次数,这样i和i-1差值的个数直接用nums[i]*nums[i+1]就可以算出,时间复杂度为O(n)
O(n)代码
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int[] nums = new int[10005];
int sum = 0;
for ( int i = 0; i < n; i++ ) nums[in.nextInt()]++;
for ( int i = 0; i < nums.length-1; i++ ) sum += nums[i]*nums[i+1];
System.out.println(sum);
}
}