首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >后续:查找数组值差等于一个数字的次数

后续:查找数组值差等于一个数字的次数
EN

Code Review用户
提问于 2014-09-17 05:03:36
回答 1查看 67关注 0票数 1

这个问题是这个问题的后续问题.

样本计算

10-21=-11 10-34=-24 10-45=-35 10-56=-46 21-10=11 < 21-34=-13 21-45=-24 21-56=-24 21-56=-35 34-10=24 34-21=-11 34-45=-22 45-10=35 45-21=11 << 45-34=11 <<< 45-56=46 56-21=35 56-34=22 56-45-45=11<<<

代码语言:javascript
复制
Set<Integer> tchars = new HashSet<>();
        tchars.add(10);
        tchars.add(21);
        tchars.add(34);
        tchars.add(45);
        tchars.add(56);
        int number = 11;
        int counter = 0;

        Iterator it = tchars.iterator();
        while (it.hasNext()) {
            Integer inte = (Integer) it.next();
            if (tchars.contains(inte + number)) {
                System.err.println(inte + " " + number);
                counter++;
            }
        }
        System.err.println(counter);
EN

回答 1

Code Review用户

发布于 2014-09-17 05:38:41

使用集合是有问题的。

首先,正如“Vogel612 612”S评论中的原始问题所指出的那样,它限制了重复值。其次,它还使代码变得更加混乱,因为您现在正在获取一个Iterator,调用.hasNext(),并在while循环中进行测试,而不是使用更简洁的语法。

我只需要使用一个List<Integer>,去掉所有的强制转换,使用一个for-每种样式的语法,而不是使用Iterator。最后,在这个片段的上下文中,numbercounter作为变量名并不是非常有意义的。如果它们在更广泛的背景下是有意义的,无论它来自何处,但我发现类似于differenceresult的东西要清晰得多。

更像是这样的:

代码语言:javascript
复制
List<Integer> tchars = Arrays.asList(10, 21, 34, 45, 56);
int difference = 11;
int result = 0;

for (int test : tchars) {
    if (tchars.contains(test + difference)) {
        System.err.println(test + " " + difference);
        result++;
    }
}

System.err.println(result);

非常简单,你可以立即看到它在做什么。

票数 2
EN
页面原文内容由Code Review提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://codereview.stackexchange.com/questions/63110

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档