增加 for 循环的计数器

huangapple go评论76阅读模式
英文:

incrementing the counter of a for-loop

问题

以下是翻译好的内容:

我在一次Hakerrank挑战中遇到了一个练习,我在其中使用了一个基本的for循环来迭代数组,然后我考虑根据条件递增循环计数器。这是我的解决方案:

public static int sockMerchant(int n, int[] ar) {
    int pairs = 0;
    Arrays.sort(ar);
    if (n % 2 != 0) n = n - 1;
    for (int i = 0; i < n - 1; i++) {
        if (ar[i] == ar[i + 1]) {
            ++pairs;
            // 递增循环计数器
            i++;
        }
    }
    return pairs;
}

我想知道在递增for循环计数器时是否会有任何影响或问题。有关已编写代码的注意事项,大家有什么想法吗?

英文:

I came by an exercise in a Hakerrank challenge where I used a basic for loop to iterate over an array, then I thought about incrementing the loop counter based on a condition. Here is my solution :

public static int sockMerchant(int n, int[] ar) {
    int pairs = 0;
    Arrays.sort(ar);
    if (n % 2 != 0) n = n - 1;
    for (int i = 0; i &lt; n - 1; i++) {
        if (ar[i] == ar[i + 1]) {
            ++pairs;
            // incrementing the loop counter
            i++;
        }
    }
    return pairs;
}

I'm wondering if there is any incidence or issues when incrementing the for-loop counter. Any ideas guys of things to be careful about with the written code?

答案1

得分: 1

不是所有的编程语言都允许修改循环的索引。如果是这种情况,可以使用适用于该语言的合适或惯用的方法。

但是,Java允许修改循环的索引。

可以查看Greg Hewgill的详细回答。

链接:https://stackoverflow.com/a/9012318/13651978

英文:

Not all programming languages allow the modification of a loop's index. If that is the case, then use whatever method that is appropriate or idiomatic for that language.

But, Java allows the modification of a loop's index.

Take a look at the detailed answer by Greg Hewgill.

https://stackoverflow.com/a/9012318/13651978

huangapple
  • 本文由 发表于 2020年7月26日 17:29:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/63098390.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定