public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int c[] = new int[n];
for(int c_i=0; c_i < n; c_i++){
c[c_i] = in.nextInt();
}
Arrays.sort(c);
int t=0;
for (int i=0;i<n-1;i++){
if(c[i]==c[i+1]){
t++;
i++;
}
}
System.out.println(t);
}
}
当我从 if 条件中删除 i++ 并在 for 循环中设置 i=i+2 时,某些测试用例的输出会发生变化。有人可以解释一下原因吗,因为在这两种情况下 i 都增加了 2。
最佳答案
仅当 c[i]==c[i+1]
时才会执行循环体内的 i++
,因此 i
是在某些迭代中增加 1
,在其他迭代中增加 2。
另一方面,循环的增量始终会执行,因此如果将循环的增量更改为 i+=2
(并且循环体内的 i++
会被删除) ),i
在每次迭代中都会增加 2。
因此
for (int i=0;i<n-1;i++){
if(c[i]==c[i+1]){
t++;
i++;
}
}
不等于
for (int i=0;i<n-1;i+=2){
if(c[i]==c[i+1]){
t++;
}
}
关于java - 这道题中增量和加法的区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60798215/